Jest 无法读取 null 的属性“createEvent" [英] Jest Cannot read property 'createEvent' of null

查看:20
本文介绍了Jest 无法读取 null 的属性“createEvent"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图模拟被拒绝的值并收到此错误.奇怪的是,这种结构在成功"的情况下有效.addUser.mockImplementation(value => jest.fn().mockResolvedValue(value)),但是当我试图用拒绝做同样的技巧时,它不起作用并说'不能读取属性 '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'

这是我的测试用例

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, 'sample@mail.com')
  })

  expect(emailInput.value).toBe('sample@mail.com')
  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?

推荐答案

这似乎是当有人谷歌搜索无法读取 null 的属性 'createEvent'"时发现的第一个问题,所以把这个答案留在这里给那些人读者:

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:

这是一个未模拟的 API 调用.
在一个钩子中进行了一个 API 调用,并且该钩子被用于测试失败的组件中.显然 Jest 在完成测试后清理了所有内容,当调用返回时,它什么也没找到,因此出错了.

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.

如果有人遇到这样的错误,请确保模拟您拥有的任何异步逻辑,尤其是当它返回时与 DOM 交互时.

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.

这篇关于Jest 无法读取 null 的属性“createEvent"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆