简体   繁体   中英

sinon stub or else for function not a method

Is there a way to use sinon.stub() just for a function without an object with a method, example,

function getSome(){}

sinon.stub(getSome)

or is there another sinon method that does this?

Short answer, there is no method of sinon to stub a standalone function directly.

Nodejs would load and cache the default exported function so no stubbing library like sinon would be able to fake/spy it unless we reload the module again in the cache object.

Here is a solution:

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);
  });
});

Unit test result with 100% coverage:

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

source code: https://github.com/mrdulin/mocha-chai-sinon-codelab/tree/master/src/stackoverflow/59064196

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM