Stubbing window features in Jest

In my code, I call the callback when I click the "OK" prompt window.confirm, and I want to check if the callback is called.

In sinonI can drown out the function window.confirmwith:

const confirmStub = sinon.stub(window, 'confirm');
confirmStub.returns(true);

Is there a way I can reach this stage in Jest?

+15
source share
2 answers

For fun, you can simply overwrite them with global.

global.confirm = () => true

As a joke, each test file is launched in its own process, you do not need to install reset.

+33
source

I just used the 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()
}
+1

Source: https://habr.com/ru/post/1667215/


All Articles