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?
spyOn() spyOn() is inbuilt into the Jasmine library which allows you to spy on a definite piece of code.
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.
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").
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.
Additionally to the other fine answer:
spyOn()
to spy (intercept) an existing method on an object to track calls of other modules to it.jasmine.createSpy()
to create a function that can be passed as callback or Promise handler to track call-backs.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With