我正在使用JEST测试来测试我的Reaction项目,该项目是用Create Reaction App创建的#tyescript编写的。我正在使用react-testing-library
。我有一个表单组件,如果表单是空提交的,它会显示alert
。我想(也许)通过监视/模仿window.alert
来测试此功能,但它不起作用。
我尝试按照许多SO答案中的建议使用jest.fn()
,但也不起作用。
window.alert = jest.fn();
expect(window.alert).toHaveBeenCalledTimes(1);
我是如何实现它的:Form.tsx
async handleSubmit(event: React.FormEvent<HTMLFormElement>) {
// check for errors
if (errors) {
window.alert('Some Error occurred');
return;
}
}
下面是我如何构建反应+Jest+反应-测试库测试:Form.test.tsx
it('alerts on submit click', async () => {
const alertMock = jest.spyOn(window,'alert');
const { getByText, getByTestId } = render(<Form />)
fireEvent.click(getByText('Submit'))
expect(alertMock).toHaveBeenCalledTimes(1)
})
我认为您可能需要稍微调整测试,将.mockImplementation()
添加到您的spyOn
中,如下所示:
it('alerts on submit click', async () => {
const alertMock = jest.spyOn(window,'alert').mockImplementation();
const { getByText, getByTestId } = render(<Form />)
fireEvent.click(getByText('Submit'))
expect(alertMock).toHaveBeenCalledTimes(1)
})