Stubbing window functions in Jest

In jest you can just overwrite them using global.

global.confirm = () => true

As in jest every test file run in its own process you don't have to reset the settings.


I just used Jest mock and it works for me :

   it("should call my function", () => {
      // use mockImplementation if you want to return a value
      window.confirm = jest.fn().mockImplementation(() => true)

      fireEvent.click(getByText("Supprimer"))

      expect(window.confirm).toHaveBeenCalled()
}

To eliminate the chances that the mocking would leak to other tests, I used a one-time mock:

jest.spyOn(global, 'confirm' as any).mockReturnValueOnce(true);