Why use spyOn instead of jasmine.createSpy?

前端 未结 2 970
春和景丽
春和景丽 2020-12-29 20:53

What is the difference between

jasmine.createSpy(\'someMethod\')

And

spyOn(someObject, \'someMethod\')

相关标签:
2条回答
  • 2020-12-29 21:16

    Additionally to the other fine answer:

    • Use spyOn() to spy (intercept) an existing method on an object to track calls of other modules to it.
    • Use jasmine.createSpy() to create a function that can be passed as callback or Promise handler to track call-backs.
    0 讨论(0)
  • 2020-12-29 21:18

    The difference is that you should have a method on the object with spyOn

    const o = { some(): { console.log('spied') } };
    spyOn(o, 'some');
    

    while the mock method is created for your with createSpy():

    const o = {};
    o.some = jasmine.createSpy('some');
    

    The advantage of the spyOn is that you can call the original method:

    spyOn(o, 'some').and.callThrough();
    o.some(); // logs 'spied'
    

    And as @estus says the original method is restored after the test in case of spyOn. This should be done manually when it's reassigned with.

    0 讨论(0)
提交回复
热议问题