如何模拟或断言window.alert是否已在带有打字稿的React&Jest中触发?

时间:2019-05-01 07:48:08

标签: reactjs typescript jestjs react-testing-library

我正在使用玩笑测试来测试我的React项目,该项目使用通过Create React App创建的#typescript编写。我正在使用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;
    }
}

这是我构建React + Jest + react-testing-library测试的方式: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)
})

2 个答案:

答案 0 :(得分:0)

您可以尝试使用global代替window

global.alert = jest.fn();
expect(global.alert).toHaveBeenCalledTimes(1);

或者,尝试Object.assign

const alert = jest.fn()
Object.defineProperty(window, 'alert', alert);

答案 1 :(得分:0)

我认为您可能需要通过将 .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)
})