Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stubbing window functions in Jest

In my code, I trigger a callback upon "OK" click of a window.confirm prompt, and I want to test that the callback is triggered.

In sinon, I can stub the window.confirm function via:

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

Is there a way I can achieve this stubbing in Jest?

like image 806
Yangshun Tay Avatar asked Jan 19 '17 02:01

Yangshun Tay


People also ask

What is stub in Jest?

Stubs are used to validate the state of a method, whereas mocks are used to evaluate the behavior. Jest provides jest. fn , which has both basic mocking and stubbing functionality. A Jest mock can also stub method outputs, and in this case be both a mock and a stub.

How do you define a window in Jest?

To mock the JavaScript window object using Jest, we can use the jest. spyOn method. let windowSpy; beforeEach(() => { windowSpy = jest. spyOn(window, "window", "get"); }); afterEach(() => { windowSpy.

How do you use spyOn function in Jest?

To spy on an exported function in jest, you need to import all named exports and provide that object to the jest. spyOn function. That would look like this: import * as moduleApi from '@module/api'; // Somewhere in your test case or test suite jest.

How do you check if a function is called in Jest?

To check if a component's method is called, we can use the jest. spyOn method to check if it's called. We check if the onclick method is called if we get the p element and call it.


1 Answers

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.

like image 184
Andreas Köberle Avatar answered Oct 06 '22 10:10

Andreas Köberle