I am a newbie to Jasmine
and a bit confused between above two functions. My sole purpose is to give a fake implementation to a spy function. But, If I put debugger in callFake
the it is getting called but and.stub
's function is not getting called. Could anyone please explain what is the difference between these two functions.
spyOn(manager, 'getUsers').and.stub(function () {
//to do
});
vs
spyOn(manager, 'getUsers').and.callFake(function () {
//to do
});
callFake() Test doubles like mocks, spies, and stubs are integral part of unit testing. In Jasmine, there are few such functions which can stub any function and track calls to it and all its arguments.
A stub replace the implementation where a spy only act has a passthrough calling the actual implementation.
spyOn() spyOn() is inbuilt into the Jasmine library which allows you to spy on a definite piece of code.
Using Jasmine spies to mock code Jasmine spies are easy to set up. You set the object and function you want to spy on, and that code won't be executed. In the code below, we have a MyApp module with a flag property and a setFlag() function exposed. We also have an instance of that module called myApp in the test.
Looking at the documentation located at https://jasmine.github.io/2.0/introduction.html#section-Spies, when you spyOn
something it logs of all the calls being made on the spied on object method. This means that it is calling the actual method of the object, but keeping track of what calls were made.
If you want to allow using the original object, but don't want specific methods to be called, you have the options of using and.callFake
and and.stub
. The differences are in the method signatures.
callFake
takes a function as a parameter. This allows you to fake the method call and return a value of your desire.
original method signature is myMethod(param1: string): string
spyOn(service, 'myMethod').and.callFake((param1) => {
expect(param1).toBe('value');
return 'returnValue';
});
stub
has no parameters and merely intercepts the call to the method
spyOn(service, 'myMethod').and.stub();
myMethod can have parameters and can have a return type, but it doesn't matter since stub just intercepts the call and will return null
if there is a return type.
In both instances, the method calls are logged and you can then do something like expect(service.myMethod).toHaveBeenCalled()
or expect(service.myMethod).toHaveBeenCalledWith('value')
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