React, Jest, and Testing Library: TypeError: Cannot read property 'createEvent' of null when using findBy such as findByAltText

Viewed 3609

Problem

When I try to run my tests via npm test using Jest, with React, and Testing Library I get the following error:

Error

/node_modules/react-dom/cjs/react-dom.development.js:3905
      var evt = document.createEvent('Event');
                         ^

TypeError: Cannot read property 'createEvent' of null
    at Object.invokeGuardedCallbackDev (/node_modules/react-dom/cjs/react-dom.development.js:3905:26)
    at invokeGuardedCallback (/node_modules/react-dom/cjs/react-dom.development.js:4056:31)
    at flushPassiveEffectsImpl (/node_modules/react-dom/cjs/react-dom.development.js:23543:11)
    at unstable_runWithPriority (/node_modules/scheduler/cjs/scheduler.development.js:468:12)
    at runWithPriority$1 (/node_modules/react-dom/cjs/react-dom.development.js:11276:10)
    at flushPassiveEffects (/node_modules/react-dom/cjs/react-dom.development.js:23447:14)
    at Object.<anonymous>.flushWork (/node_modules/react-dom/cjs/react-dom-test-utils.development.js:992:10)
    at Immediate.<anonymous> (/node_modules/react-dom/cjs/react-dom-test-utils.development.js:1003:11)
    at processImmediate (node:internal/timers:464:21)
/node_modules/react-dom/cjs/react-dom.development.js:3905
      var evt = document.createEvent('Event');
1 Answers

It was Testing Library all along

After nearly losing my sanity, I found out the resolve to this is quite simple. I accidentally allowed my IDE to autocomplete to findByAltText rather than what I normally use: getByAltText. The findBy requires the test to be async and the call to have await.

Broken

 it('displays the logo', () => {
    const logo = screen.findByAltText('Logo')
    expect(logo).toBeInTheDocument()
  })

Fixed

Needs: async and await when using findBy

 it('displays the logo', async () => {
    const logo = await screen.findByAltText('Logo')
    expect(logo).toBeInTheDocument()
  })

Another Option

Just use the getBy like I am used to!

 it('displays the logo', () => {
    const logo = screen.getByAltText('Logo')
    expect(logo).toBeInTheDocument()
  })

Bonus

Through my research I found: eslint-plugin-testing-library, it can at least warn you about this problem through your linter. Make sure to follow its setup.

https://github.com/testing-library/eslint-plugin-testing-library

Related