如何模拟或断言window.ert是否已在带有TypeScrip的Reaction&Jest中触发? [英] How to mock or assert whether window.alert has fired in React & Jest with typescript?

查看:0
本文介绍了如何模拟或断言window.ert是否已在带有TypeScrip的Reaction&Jest中触发?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用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)
})

这篇关于如何模拟或断言window.ert是否已在带有TypeScrip的Reaction&amp;Jest中触发?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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