【问题标题】:How to verify the call to super using sinonjs?如何使用 sinonjs 验证对 super 的调用?
【发布时间】:2019-02-15 15:54:16
【问题描述】:

我有一个扩展另一个类 (BBB) 的 javascript/typescript 类 (AAA)。 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】:

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

    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);
            });
        });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-07-20
      • 1970-01-01
      • 1970-01-01
      • 2021-07-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多