Matt Downey Matt Downey -4 years ago 122
TypeScript Question

Jasmine spying on method that calls external method (Angular 2)

In my angular 2 app, How do I test if my external method (dependency) inside my main method is being called accordingly.

For instance,



Class ServiceA
{
constructor(
private serviceB : ServiceB
){}


//How do I test this method to make sure it does what it should ?
mainMethod()
{
//External method
this.serviceB.otherMethod();

this.sideMethod();
}

sideMethod()
{
//Do something
}
}

Class ServiceB
{
constructor(){}

otherMethod()
{
//Do something
}
}





Here's what I've tried so far



it('On otherMethod returns false, do something',
inject([ServiceA, ServiceB], (serviceA: ServiceA, serviceB: ServiceB) => {
spyOn(serviceB, 'otherMethod').and.returnValue(false);
spyOn(serviceA, 'sideMethod');
spyOn(serviceA, 'mainMethod').and.callThrough();


expect(serviceB.otherMethod()).toHaveBeenCalled();
expect(serviceA.sideMethod()).toHaveBeenCalled();
expect(serviceA.mainMethod()).toHaveBeenCalled();
}));





From above code, I got an error stating that it 'could not find an object to spy upon for otherMethod()'

What is wrong here ?

Answer Source

You have to pass the function reference of your spy serviceB.otherMethod. You are currently invoking the spy by calling serviceB.otherMethod() which will return the return value of otherMethod instead of the spy.

it('On otherMethod returns false, do something', 
    inject([ServiceA, ServiceB], (serviceA: ServiceA, serviceB: ServiceB) => {
    spyOn(serviceB, 'otherMethod').and.returnValue(false);
    spyOn(serviceA, 'sideMethod');
    spyOn(serviceA, 'mainMethod').and.callThrough();

    // Notice spy reference here instead of calling it.
    expect(serviceB.otherMethod).toHaveBeenCalled();
    expect(serviceA.sideMethod).toHaveBeenCalled();
    expect(serviceA.mainMethod).toHaveBeenCalled();
}));

Jasmine documentation: https://jasmine.github.io/2.0/introduction.html#section-Spies

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download