【问题标题】:TypeError: Cannot read property 'createEvent' of null React Apollo testingTypeError:无法读取 null React Apollo 测试的属性“createEvent”
【发布时间】:2021-06-09 06:29:19
【问题描述】:

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

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');
  });
});

【问题讨论】:

    标签: reactjs typescript jestjs enzyme apollo-client


    【解决方案1】:

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

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

    这是因为 测试在完成后会中断组件执行,并且会干扰我发送的 in progress Mutation。所以,我只需要在测试结束时添加一些断言(这就是我们有测试的原因):

    测试

    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);
      });
    });
    

    【讨论】:

    • 补充一点,我在async 测试中遇到了同样的问题,我将我的期望包装在await waitFor() 中......所以看起来你不应该在测试 React Apollo 突变
    • 什么意思?我不应该使用什么?
    • 你的意思是我应该做测试来测试 Apollo 案例还是不使用await waitFor
    猜你喜欢
    • 2022-10-21
    • 2020-06-15
    • 2019-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多