你不能打电话sinon.spy
or 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