如何模拟或断言window.ert是否已在带有TypeScrip的Reaction&Jest中触发?已在、断言、ert、window

2023-09-03 14:44:07 作者:木棺里消失的尸体

我正在使用JEST测试来测试我的Reaction项目,该项目是用Create Reaction App创建的#tyescript编写的。我正在使用react-testing-library。我有一个表单组件,如果表单是空提交的,它会显示alert。我想(也许)通过监视/模仿window.alert来测试此功能,但它不起作用。

我尝试按照许多SO答案中的建议使用jest.fn(),但也不起作用。

window.alert = jest.fn();
expect(window.alert).toHaveBeenCalledTimes(1);
版本号9374新截图暗示还有Windows RT 8.1预览版和Windows Se

我是如何实现它的: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)
})