reactjs - 如何在 React 與 Jest 中使用 TypeScript 模擬或斷言 window.alert 是否已觸發?
我正在使用 jest 測試來測試我用 Create React App 創建的 #typescript 編寫的 React 專案。我正在使用 react-testing-library。我有一個表單組件,如果表單為空提交,它會顯示一個 alert。我想測試這個功能(也許)通過監視/模擬 window.alert,但它不起作用。
我嘗試按照許多 Stack Overflow 的答案使用 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)
})
答案#1
我覺得你可能需要稍微調整你的測試,在你的 spyOn 中加入 .mockImplementation(),像這樣:
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)
})
答案#2
你可以嘗試使用 global 取代 window:
global.alert = jest.fn();
expect(global.alert).toHaveBeenCalledTimes(1);
或者,試試 Object.assign
const alert = jest.fn()
Object.defineProperty(window, 'alert', alert);
