Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest Cannot read property 'createEvent' of null

I was trying to mock rejected value and got this error. It's weird that this construction works in the case of "success" addUser.mockImplementation(value => jest.fn().mockResolvedValue(value)), but when I'm trying to do the same trick with rejecting, it doesn't work and says 'Cannot read property 'createEvent' of null'

Here is my test case

it('receives invalid value and throws an error', async () => {
  addUser.mockImplementation(() =>
    jest.fn().mockRejectedValue(new Error('Sample error'))
  )

  const enqueueSnackbar = jest.fn()
  useSnackbar.mockReturnValue({ enqueueSnackbar })

  const { emailInput, form, submitButton } = setup()

  await act(async () => {
    fillIn(emailInput, '[email protected]')
  })

  expect(emailInput.value).toBe('[email protected]')
  expect(submitButton).toHaveProperty('disabled', false)

  await act(async () => {
    fireEvent.submit(form)
  })

  expect(enqueueSnackbar).toHaveBeenCalledTimes(1)
  expect(enqueueSnackbar).toHaveBeenCalledWith(`Sample error`, {
    variant: 'error'
})})

Does anyone know how to make it work?

like image 963
Ingrid Avatar asked Mar 03 '20 10:03

Ingrid


2 Answers

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.

like image 175
cst1992 Avatar answered Nov 14 '22 04:11

cst1992


Similar to what @alexandre_anicio stated. I was getting this error when using the findAllByText query. expect(screen.findAllByText('word'))...

When I switched to the getAllByText the error went away and the test passed. expect(screen.getAllByText('word'))...

If I used expect(await screen.findAllByText('word'))... I noticed the test passed as well.

Digging deeper, this is because findBy tests return a promise so the await is needed. https://testing-library.com/docs/guide-disappearance/#1-using-findby-queries

It would have been nice for the library to throw a better error however.

like image 25
Sark Peha Avatar answered Nov 14 '22 05:11

Sark Peha