What's Spying on JS Testing?
Saikat Saha
Frontend Developer at PayPal | Oracle | ANZ | JP Morgan - JavaScript, HTML5, CSS3, ReactJS, React Native, MERN, NodeJS, PhoneGap, Cross Platform Mobile, Data Structure, Algorithm, System Design, Full Stack - NodeJS
We all know that Jasmine is a unit-testing framework and it works only on logics but do you know whether it can spy on APIs, DOMs and Third-Party libraries?
Yes, it can do it, I can explain it by writing a very simple code snippet where I'm alerting a text
it('Spy Alert Test Case', () => {
spyOn(window, 'alert'); // spyOn method will mimic on the DOM's window object
// execute the alert
expect(window.alert).toHaveBeenCalled(); // check the alert execution
expect(window.alert).toHaveBeenCalledWith('Alert Text'); // check the alert execution with alert text
})
Similarly I can show you another example using 'Confirm' method
it('Spy Confirm Test Case', () => {
spyOn(window, 'confirm').and.returnValue(true); // spyOn method will mimic on the DOM's window object
// execute the confirm statement
expect(window.confirm).toBe('Condition Text'); // check the 'confirm' execution and based on the response, we're checking the result
})
These are just basic examples, we can use spyOn for multiple scenarios