sinon stub或其他功能不是方法

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

例如,有没有一种方法可以将sinon.stub()仅用于不带对象的带有函数的函数,

function getSome(){}

sinon.stub(getSome)

或者还有另一种可以这样做的sinon方法吗?

javascript sinon
1个回答
0
投票

Node.js将加载并缓存默认的导出函数,因此除非我们再次将模块重新加载到缓存对象中,否则像sinon这样的存根库都无法伪造/监视它。

这里是解决方法:

mod.ts

module.exports = function getSome() {
  console.log("real get some");
};

index.ts

const getSome = require("./mod");

module.exports = function main() {
  return getSome();
};

index.spec.ts

import sinon from "sinon";
import { expect } from "chai";

describe("getSome", () => {
  it("should stub", () => {
    const getSomeStub = sinon.stub().returns("stub get some");
    require.cache[require.resolve("./mod.ts")] = {
      exports: getSomeStub,
    };
    const main = require("./");
    const actual = main();
    expect(actual).to.be.equal("stub get some");
    sinon.assert.calledOnce(getSomeStub);
  });
});

单元测试结果覆盖率100%:

 getSome
    ✓ should stub (88ms)


  1 passing (93ms)

---------------|----------|----------|----------|----------|-------------------|
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/59064196

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