Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between and.stub vs and.callFake in Jasmine

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
    });
like image 750
Ankush Jain Avatar asked Mar 18 '18 06:03

Ankush Jain


People also ask

What does callFake do in Jasmine?

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.

What is a stub in Jasmine?

A stub replace the implementation where a spy only act has a passthrough calling the actual implementation.

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.

How do you mock a method in Jasmine?

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.


1 Answers

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')

like image 141
Jon Tinsman Avatar answered Sep 20 '22 11:09

Jon Tinsman