I am using jest tests to test my React project written in #typescript created with Create React App. I'm using react-testing-library
. I have a form component which shows an alert
if the form is submitted empty. I wanted to test this feature (maybe) by spying/mocking the window.alert
but it doesn't work.
I tried using jest.fn()
as suggested in many SO answers but that's not working too.
window.alert = jest.fn();
expect(window.alert).toHaveBeenCalledTimes(1);
Here's how I implemented it: Form.tsx
async handleSubmit(event: React.FormEvent<HTMLFormElement>) {
// check for errors
if (errors) {
window.alert('Some Error occurred');
return;
}
}
Here's how I built the React+Jest+react-testing-library test: 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)
})