TypeError:无法读取空反应Apollo测试的属性'createEvent' [英] TypeError: Cannot read property 'createEvent' of null React Apollo testing

查看:13
本文介绍了TypeError:无法读取空反应Apollo测试的属性'createEvent'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到一个错误,最终导致Reaction组件的测试崩溃。我使用Apollo钩子进行突变useMutation,使用酶进行按ID查找组件。

repo code
ode_modules
eact-domcjs
eact-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);
  });
});

这篇关于TypeError:无法读取空反应Apollo测试的属性&#39;createEvent&#39;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆