32

I'm currently having an issue when spying on inherited methods for calls in typescript classes, where the toHaveBeenCalled() method is returning false, even though the method being spied upon is called. Look at the following scenario...

I have two classes, written in TypeScript

class Parent() {
    buyFood() {
        // buy food
    }
}

class Husband extends Parent {
    makeDinner() {
        super.buyFood();
        // make dinner;
    }
}

In my tests for the class Husband, i'm only concerned of testing the logic for making dinner, since the logic of the buy food of the super class is tested in its own test suite.

Hence, my tests looks like something of the following sort.

let husband:Husband = new Husband();

it('Should make a good dinner', () => {
    spyOn(husband, 'buyFood');
    husband.makeDinner();

    expect(husband.buyFood).toHaveBeenCalled();
}

Even though buyFood() is being called, the assertion is failing with an error saying that husband.buyFood() which is the method inherited from the Parent class has never been called.

How should I go about this issue, without having to assert the value changes by the buyFood() method call?

3
  • Is it documented anywhere that this is supported by the testing framework? Inheritance in JavaScript is fickle at best. Commented Jan 26, 2017 at 8:41
  • There does not seem to be any reference to inherited methods... From the docs "A spy can stub any function and tracks calls to it and all arguments." Commented Jan 26, 2017 at 8:54
  • Then perhaps it is not walking the prototype chain. Commented Jan 26, 2017 at 8:56

4 Answers 4

73

You have to understand the mechanics behind Typescript and the spying.

First on Typescript ...

I'm ignoring the extra parens in class Parent().

Typescript uses prototypal inheritance behind the curtain. Thus a prototype will copy the referenced properties from the "base class" to the new class. This is what the for loop does in the __extends() function.

This is the ES5 code your Typescript is translated to:

var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var Parent = (function () {
    function Parent() {
    }
    Parent.prototype.buyFood = function () {
        // buy food
    };
    return Parent;
}());
var Husband = (function (_super) {
    __extends(Husband, _super);
    function Husband() {
        return _super.apply(this, arguments) || this;
    }
    Husband.prototype.makeDinner = function () {
        _super.prototype.buyFood.call(this);
        // make dinner;
    };
    return Husband;
}(Parent));

You can translate typescript using this Typescript playground.

Your super expression calls the buyFood() method of the parent class and not the method of the "inherited" Husband.

See the line

_super.prototype.buyFood.call(this);

and follow the _super reference.

Now Jasmine Spies ...

A spy will replace the named function of the passed object by a spy function that will act as a proxy. That proxy can now track calls and, depending on the programmed behavior, control whether to call the original function, a fake, return a value or do nothing (default).

A very simplified spyOn() could look like this:

function spyOn(obj, fn) {
    var origFn = obj[fn],
        spy = function() {
            spy.calls.push(arguments);
        };

    spy.calls = [];

    obj[fn] = spy;
}

The actual spy method is much more complex though.

Your line

spyOn(husband, 'buyFood');

will actually replace the method in the instance of Husband by a spy. But, since the code calls the reference of the base class (the parent prototype) it's not the same function that you've just replaced.

Solution

You should either call the this referenced method

class Husband extends Parent {
    makeDinner() {
        // call byFood() via this
        this.buyFood();
    }
}

... or spy on the parent prototype (super):

it('Should make a good dinner', () => {
    spyOn(Parent.prototype, 'buyFood');
    husband.makeDinner();

    expect(Parent.prototype.buyFood).toHaveBeenCalled();
}
6
  • Super!! Thanks a lot for the details explanation and solution! Really really grateful! :D Commented Jan 30, 2017 at 7:53
  • 1
    This was extremely helpful! In my case I have a method in a subclass that shadows a super class named method, so the spyOn(Parent.prototype, 'methodName'); was perfect!
    – lukiffer
    Commented Jan 15, 2018 at 20:15
  • 1
    The solution worked perfectly! Most importantly, thanks for neatly explaining why it works :)
    – Martin
    Commented Jul 31, 2019 at 2:02
  • Wow. Love this solution! Commented Feb 3, 2020 at 16:50
  • @try-catch-finally what about if buyFood() is "protected" ?
    – strix25
    Commented Apr 29, 2020 at 14:52
9

When using ES6, the Parent.prototype will not work. Use the Object.getPrototypeOf instead.

This is what worked for me:

it('Should make a good dinner', () => {
    spyOn(Object.getPrototypeOf(Object.getPrototypeOf(husband)), 'buyFood');
    husband.makeDinner();

    expect(Parent.prototype.buyFood).toHaveBeenCalled();
}
4
  • works for me, but strange that Object.getPrototypeOf() must be called twice
    – tedw
    Commented Mar 23, 2020 at 21:55
  • i think this is because the 1st call will get you the prototype of the class and the 2nd call will get you the prototype's prototype
    – bobbyg603
    Commented Sep 15, 2020 at 17:03
  • P.S. This solution works, except your example is missing a trailing parenthesis after 'husband'.
    – MrGrigri
    Commented Dec 11, 2020 at 16:38
  • This is fantastic — thank you! I used this recently to spy on the super of a directive in Angular. Might not have gotten there without this gem <3 Commented Jun 14, 2023 at 22:41
0
const spy = spyOn(husband, 'buyFood');
husband.makeDinner();
expect(spy).toHaveBeenCalled();
1
  • It would be good to add a sentence to explain what was wrong and what the proposed code is fixing Commented Aug 13, 2020 at 12:25
0

The realworld example

// test-utils.ts
function spyOnParentClassMethod<T, K extends keyof T = keyof T> (
    instance: T,
    method: T[K] extends Function ? K : never,
){
    const parentInstance: T = Object.getPrototypeOf(Object.getPrototypeOf(instance));
    return spyOn(parentInstance, method);
}

// spec.ts
const spy = spyOnParentClassMethod(husband, 'buyFood');
husband.makeDinner();
expect(spy).toHaveBeenCalled();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.