sinon - 监视 toString 方法

2023-12-12

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

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

我怎样才能监视toString从我的测试文件?我知道如何监视像 parseInt 这样的东西:

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

但这不起作用toString因为它被称为值,所以我尝试监视Object and Object.prototype,但这也行不通。


你不能打电话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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

sinon - 监视 toString 方法 的相关文章

随机推荐