What's Spying on JS Testing?

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


要查看或添加评论,请登录

Saikat Saha的更多文章

  • is 'Assertion' a confusing term?

    is 'Assertion' a confusing term?

    It's very obvious for many developers to be scared or confused about the term called 'assertion'. Most of us in the…

  • Debugging tips in Jasmine

    Debugging tips in Jasmine

    We all know that Jasmine is a very popular unit testing framework for JavaScript, do we all know that there is…

社区洞察

其他会员也浏览了