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

Viewed 6987

I am getting an error that eventually crashes test of a react component. I am using Apollo hook for mutation useMutation and Enzyme for component find by 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

Component

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

Test

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

After some digging, the problem was that I did not finish my test with any assertion.

So even just a simple expect for any item or just a blank await new Promise() will prevent test from crashing.

This is because the test breaks the component execution after it finishes and that intervenes with in progress Mutation that I have sent. So, I just needed to add some assertion at the end of the test (that is why we have the tests after all):

Test:

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