Mayur Dhurpate
Mayur Dhurpate

Reputation: 1282

How to mock or assert whether window.alert has fired in React & Jest with typescript?

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)
})

Upvotes: 10

Views: 15728

Answers (2)

George
George

Reputation: 173

I think you might need to tweak your test ever so slightly by adding .mockImplementation() to your spyOn like so:

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)
})

Upvotes: 14

Raffaele Abramini
Raffaele Abramini

Reputation: 141

You could try to use global instead of window:

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

Alternatively, try to Object.assign

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

Upvotes: 5

Related Questions