如何使用打字稿模拟或断言 window.alert 是否在 React & Jest 中触发?

May*_*ate 10 typescript reactjs jestjs react-testing-library

我正在使用玩笑测试来测试用 Create React App 创建的 #typescript 编写的 React 项目。我在用着react-testing-library。我有一个表单组件,它显示alert表单是否提交为空。我想通过监视/嘲笑来测试此功能(也许),window.alert但它不起作用。

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

window.alert = jest.fn();
expect(window.alert).toHaveBeenCalledTimes(1);
Run Code Online (Sandbox Code Playgroud)

这是我的实现方式:Form.tsx

async handleSubmit(event: React.FormEvent<HTMLFormElement>) {
   // check for errors
    if (errors) {
        window.alert('Some Error occurred');
        return;
    }
}
Run Code Online (Sandbox Code Playgroud)

以下是我构建 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)
})
Run Code Online (Sandbox Code Playgroud)

小智 14

.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)
})
Run Code Online (Sandbox Code Playgroud)


小智 5

您可以尝试使用global而不是window

global.alert = jest.fn();
expect(global.alert).toHaveBeenCalledTimes(1);
Run Code Online (Sandbox Code Playgroud)

或者,尝试Object.assign

const alert = jest.fn()
Object.defineProperty(window, 'alert', alert);
Run Code Online (Sandbox Code Playgroud)