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

IT技术 reactjs typescript jestjs react-testing-library
2021-05-01 20:47:04

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

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

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个回答

我认为您可能需要通过添加以下内容.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)
})

您可以尝试使用global代替window

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

或者,尝试 Object.assign

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