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

问题描述 投票:0回答:1

我有一个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的调用。

javascript typescript unit-testing class sinon
1个回答
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);
        });
    });
});
© www.soinside.com 2019 - 2024. All rights reserved.