首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >sinon - spy on toString方法

sinon - spy on toString方法
EN

Stack Overflow用户
提问于 2018-04-17 04:58:51
回答 1查看 550关注 0票数 1

在我的文件中,我有这样的东西:

代码语言:javascript
复制
if(somevar.toString().length == 2) ....

如何从我的测试文件中窥探toString?我知道如何监视像parseInt这样的东西:

代码语言:javascript
复制
let spy = sinon.spy(global, 'parseInt')

但这不适用于toString,因为它是在值上调用的,我尝试过监视ObjectObject.prototype,但也不起作用。

EN

回答 1

Stack Overflow用户

发布于 2019-11-20 14:02:21

您不能对原始值的方法调用sinon.spysinon.stub,如下所示:

sinon.spy(1, 'toString')。这是错误的。

您应该在原始值的Class.prototype上调用它们。以下是单元测试解决方案:

index.ts

代码语言:javascript
复制
export function main(somevar: number) {
  if (somevar.toString(2).length == 2) {
    console.log("haha");
  }
}

index.spec.ts

代码语言:javascript
复制
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%覆盖率的单元测试结果:

代码语言:javascript
复制
  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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49866123

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档