8

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
    });
Ankush Jain
  • 4,219
  • 4
  • 23
  • 48
  • 1
    One of the things to note is your example passes a function to the `stub()` method; however, there is no method signature for stub that accepts a parameter. That is the first hint. – Jon Tinsman May 30 '18 at 23:39

1 Answers1

17

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

Jon Tinsman
  • 506
  • 3
  • 21