Jest Cannot read property ‘createEvent’ of null

This seems to be the #1 question that is found when someone Googles “Cannot read property ‘createEvent’ of null”, so leaving this answer here for those readers:

For me this error came in the midst of a test.

When executing a series of tests, some test or the other used to fail with this error, with no indication of where things went wrong. But the answer turned out to be not the test but the component itself:

It was an unmocked API call.

There was an API call being made in a hook and that hook was used in the component with the failing tests. Obviously Jest cleaned up everything after completing its test, and when the call returned, it found nothing so it errored out.

Mocking the hook solved the issue.

If someone comes across such an error, make sure to mock any asynchronous logic you have, especially if it interacts with the DOM when it returns.

Leave a Comment