sinon-监视toString方法

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

在我的文件中,我有这样的内容:

if(somevar.toString().length == 2) ....

如何从测试文件中监视toString?我知道如何使用以下方法监视parseInt之类的东西:

let spy = sinon.spy(global, 'parseInt')

但是由于toString被调用,所以它不起作用,我尝试监视ObjectObject.prototype,但这也不起作用。

node.js unit-testing sinon spy
1个回答
0
投票

您不能在像这样的原始值方法上调用sinon.spysinon.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

© www.soinside.com 2019 - 2024. All rights reserved.