如何使用sinonjs验证对super的调用?

时间:2019-02-15 15:54:16

标签: javascript typescript unit-testing class sinon

我有一个javascript / typescript类(AAA),它扩展了另一个类(BBB)。类BBB的API稳定,但实现方式尚未实现。我只想对类AAA中的某些函数进行单元测试。因此,我需要创建类AAA的实例,但由于调用类BBB的构造函数而尚未成功。这是我的example

BBB.ts:

class BBB {
    constructor() {
        throw new Error("BBB");
    }
    public say(msg: string): string {
        return msg;
    }
}

module.exports = BBB;

AAA.ts:

const BB = require("./BBB");

class AAA
    extends BB {
    public hello(): string {
        return super.say("Hello!");
    }
}
module.exports = AAA;

测试脚本:

const AA = require("../src/AAA");

import sinon from "sinon";

describe("Hello Sinon", () => {
    describe("#hello", () => {
        it("#hello", async () => {
            const stub = sinon.stub().callsFake(() => { });
            Object.setPrototypeOf(AA, stub);
            let a = new AA();

            sinon.spy(a, "hello");

            a.hello();

            sinon.assert.calledOnce(a.hello);
            sinon.assert.calledOnce(stub);

            // how to verify that super.say has been called once with string "Hello!"?
        });
    });
});

我正在使用sinonjs。但是在这种情况下,我无法创建AAA的实例。如果可以的话,如何验证super.say函数已被调用?

谢谢!

更新:现在,我可以创建AAA的实例,但是我不知道如何验证对super.say的调用。

1 个答案:

答案 0 :(得分:0)

我找到了解决问题的方法:

describe("Hello Sinon", () => {
    describe("#hello", () => {
        it("#hello", async () => {
            const stub = sinon.stub().callsFake(() => { });
            Object.setPrototypeOf(AA, stub);
            let a = new AA();
            const say = sinon.spy(a.__proto__.__proto__, "say");

            sinon.spy(a, "hello");

            a.hello();
            a.hello();

            sinon.assert.calledTwice(a.hello);
            sinon.assert.calledOnce(stub);
            sinon.assert.calledTwice(say);
        });
    });
});