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?
addUser
function look like? It looks like maybe you wantadduser.mockImplementation(() => Promise.reject(new Error('Sample error')))
which means "when add user is called, return a rejected promise with the sample error" whereas the current test code means "when add user is called, return a function, that, when it is called, returns a rejected promise with the sample error". I'm guessing that you want the first, but it's hard to know without seeing theaddUser
function. – ProverbsaddUser.mockRejectedValue(new Error('Sample error'))
which is the same asaddUser.mockImplementation(() => Promise.reject(new Error('Sample error')))
– ProverbsmyElement.dispatchEvent(new CustomEvent('click', { bubbles: true }))
, which I was doing because of some weird code outside my control that ignore click events. Guess that's not gonna work either. :/ just commenting here for the tiny chance that someone else tries the same thing and sees this error – Lankford