如何使用 sinonjs 验证对 super 的调用?
How to verify the call to super using sinonjs?
我有一个 javascript/typescript class (AAA
) 扩展另一个 class (BBB
)。 class BBB
的 API 是稳定的,但尚未实现。我只想对 class AAA
中的一些函数进行单元测试。所以我需要创建一个 class AAA
的实例,但由于调用了 class 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
.[=25 的调用=]
我找到了解决问题的方法:
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);
});
});
});
我有一个 javascript/typescript class (AAA
) 扩展另一个 class (BBB
)。 class BBB
的 API 是稳定的,但尚未实现。我只想对 class AAA
中的一些函数进行单元测试。所以我需要创建一个 class AAA
的实例,但由于调用了 class 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
.[=25 的调用=]
我找到了解决问题的方法:
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);
});
});
});