我试图模拟被拒绝的值并收到此错误。奇怪的是,这种构造在“成功”的情况下有效addUser.mockImplementation(value => jest.fn().mockResolvedValue(value))
,但是当我尝试用拒绝做同样的技巧时,它不起作用并说“无法读取 null 的属性 'createEvent'”
这是我的测试用例
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'
})})
Run Code Online (Sandbox Code Playgroud)
有谁知道如何使它工作?