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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With