TypeError: Cannot read property 'createEvent' of null React Apollo testing

TypeError: Cannot read property 'createEvent' of null React Apollo testing

我收到一个最终使反应组件测试崩溃的错误。我正在使用 Apollo hook 进行突变 useMutation,并使用 Enzyme 进行组件查找。

repo code\node_modules\react-dom\cjs\react-dom.development.js:154
      var evt = document.createEvent('Event'); // Keeps track of whether the user-provided callback threw an error. We
                         ^

TypeError: Cannot read property 'createEvent' of null

组件

import React, { useEffect } from "react";
import { useMutation } from "@apollo/react-hooks";

export const MyComponent = () => {
  const [updateUser, { data: updateUserData }] = useMutation(GQL_UPDATE_USER);

  // Update user mutation data hook
  useEffect(() => {
    if (updateUserData?.success) {
      console.log("SUCCESS");
    }
  }, [updateUserData]);

  return (
    <button
      onClick={() => {
        updateUser({
          variables: {
            id: 1,
            name: "New name",
          },
        });
      }}
    >
      Submit
    </button>
  );
};

测试

import React from 'react';
import { act, cleanup } from '@testing-library/react';
import { mount } from 'enzyme';
import { MockedProvider } from '@apollo/client/testing';

afterEach(cleanup);

it('Should submit user update', async () => {
  await act(async () => {
    const componentWrapper = mount(
      <MockedProvider mocks={someMockData} addTypename={false}>
        <MyComponent />
      </MockedProvider>,
    );

    const button = componentWrapper.find('#button');

    button.simulate('click');
  });
});

经过一番挖掘,问题是我没有用任何断言完成我的测试

因此,即使是任何项目的简单 expect 或空白 await new Promise() 也可以防止测试崩溃。

这是因为测试在完成后中断了组件执行,并且干预了正在进行的突变 我已经发送了。所以,我只需要 在测试结束时添加一些断言 (这就是我们毕竟有测试的原因):

测试:

import React from "react";
import { act, cleanup } from "@testing-library/react";
import { mount } from "enzyme";

afterEach(cleanup);

it("Should submit user update", async () => {
  await act(async () => {
    const componentWrapper = mount(<MyComponent />);

    const button = componentWrapper.find("#button");

    button.simulate("click");

    expect(button.length).toBe(1);
  });
});