在我的文件中,我有这样的东西:
if(somevar.toString().length == 2) ....如何从我的测试文件中窥探toString?我知道如何监视像parseInt这样的东西:
let spy = sinon.spy(global, 'parseInt')但这不适用于toString,因为它是在值上调用的,我尝试过监视Object和Object.prototype,但也不起作用。
发布于 2019-11-20 14:02:21
您不能对原始值的方法调用sinon.spy或sinon.stub,如下所示:
sinon.spy(1, 'toString')。这是错误的。
您应该在原始值的Class.prototype上调用它们。以下是单元测试解决方案:
index.ts
export function main(somevar: number) {
if (somevar.toString(2).length == 2) {
console.log("haha");
}
}index.spec.ts
import { main } from "./";
import sinon from "sinon";
import { expect } from "chai";
describe("49866123", () => {
afterEach(() => {
sinon.restore();
});
it("should log 'haha'", () => {
const a = 1;
const logSpy = sinon.spy(console, "log");
const toStringSpy = sinon.stub(Number.prototype, "toString").returns("aa");
main(a);
expect(toStringSpy.calledWith(2)).to.be.true;
expect(logSpy.calledWith("haha")).to.be.true;
});
it("should do nothing", () => {
const a = 1;
const logSpy = sinon.spy(console, "log");
const toStringSpy = sinon.stub(Number.prototype, "toString").returns("a");
main(a);
expect(toStringSpy.calledWith(2)).to.be.true;
expect(logSpy.notCalled).to.be.true;
});
});100%覆盖率的单元测试结果:
49866123
haha
✓ should log 'haha'
✓ should do nothing
2 passing (28ms)
---------------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
---------------|----------|----------|----------|----------|-------------------|
All files | 100 | 100 | 100 | 100 | |
index.spec.ts | 100 | 100 | 100 | 100 | |
index.ts | 100 | 100 | 100 | 100 | |
---------------|----------|----------|----------|----------|-------------------|源代码:https://github.com/mrdulin/mocha-chai-sinon-codelab/tree/master/src/stackoverflow/49866123
https://stackoverflow.com/questions/49866123
复制相似问题