Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use spyOn instead of jasmine.createSpy?

Tags:

jasmine

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?

like image 907
Payerl Avatar asked Jul 13 '17 07:07

Payerl


People also ask

What is the use of spyOn in Jasmine?

spyOn() spyOn() is inbuilt into the Jasmine library which allows you to spy on a definite piece of code.

What is createSpy Jasmine?

Jasmine's createSpy() method is useful when you do not have any function to spy upon or when the call to the original function would inflict a lag in time (especially if it involves HTTP requests) or has other dependencies which may not be available in the current context.

How do you get spyOn property in Jasmine?

In Jasmine, you can do anything with a property spy that you can do with a function spy, but you may need to use different syntax. Use spyOnProperty to create either a getter or setter spy. it("allows you to create spies for either type", function() { spyOnProperty(someObject, "myValue", "get").

What is callThrough in Jasmine?

callThrough spy. This spy will track calls to the function it is spying on, but it will also pass through to the function and allow it to run. This means that when we use this spy, the function being spied on will still do what it is written to do, but we can track the calls to it.


2 Answers

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.
like image 21
try-catch-finally Avatar answered Sep 28 '22 11:09

try-catch-finally


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.

like image 127
Max Koretskyi Avatar answered Sep 28 '22 10:09

Max Koretskyi