Why use spyOn instead of jasmine.createSpy?

15,599

Solution 1

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.

Solution 2

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.
Share:
15,599
Payerl
Author by

Payerl

Software engineer with a passion for Angular, Nodejs, Java and Deep Learning

Updated on June 14, 2022

Comments

  • Payerl
    Payerl about 2 years

    What is the difference between

    jasmine.createSpy('someMethod')

    And

    spyOn(someObject, 'someMethod')

    And why should one choose to use spyOn?

    My guess is that the first alternative will match the method someMethod no matter in what object it's contained but spyOn will only match if it's contained in someObject. Thus making createSpy just a more generic matcher?

  • Estus Flask
    Estus Flask almost 7 years
    More importantly, original method is restored after the test in case of spyOn. This should be done manually when it's reassigned with o.some = .
  • aj go
    aj go over 3 years
    @EstusFlask just want to clarify your statement, when using spyOn, after the it() executes, it will restore the spied method's original implementation?
  • Estus Flask
    Estus Flask over 3 years
    @ajgo It won't, unless you take care of it - and you need to because it's a good practice. jest.restoreAllMocks and restoreMocks config option are responsible for that.
  • aj go
    aj go over 3 years
    Does it mean spyOn will not unspy at the end of test execution? Btw I'm not using jest...i use karma-jasmine