I'm writing unit tests and I have a module file like so:
#!/usr/bin/env node
const shelljs = require('shelljs');
const bulkUpdateDependencies = (outdatedPackages) => {
// some logic
return ({});
};
module.exports = bulkUpdateDependencies;
In the test file I require it but when I try to do this:
const bulkUpdateDependencies = require('../src/bulk-update-dependencies');
bulkUpdateDependenciesStub = sandbox.stub(bulkUpdateDependencies);
bulkUpdateDependenciesStub.returns({});
I get this:
bulkUpdateDependencies.returns is not a function
Please advise on how do I properly stub bulkUpdateDependencies
function?
I guess you want to stub a standalone function directly. Here is the solution:
bulk-update-dependencies.js
:
const bulkUpdateDependencies = (outdatedPackages) => {
return {};
};
module.exports = bulkUpdateDependencies;
bulk-update-dependencies.spec.js
:
const sinon = require("sinon");
describe("59435659", () => {
let sandbox;
before(() => {
sandbox = sinon.createSandbox();
});
afterEach(() => {
sinon.restore();
});
it("should pass", () => {
const bulkUpdateDependenciesStub = sandbox.stub().returns("stubbed data");
require.cache[require.resolve("./bulk-update-dependencies.js")] = {
exports: bulkUpdateDependenciesStub,
};
const bulkUpdateDependencies = require("./bulk-update-dependencies.js");
const actual = bulkUpdateDependencies();
expect(actual).to.be.equal("stubbed data");
sinon.assert.calledOnce(bulkUpdateDependenciesStub);
});
});
Unit test result with coverage report:
59435659
✓ should pass
1 passing (7ms)
----------------------------------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
----------------------------------|----------|----------|----------|----------|-------------------|
All files | 100 | 100 | 100 | 100 | |
bulk-update-dependencies.spec.js | 100 | 100 | 100 | 100 | |
----------------------------------|----------|----------|----------|----------|-------------------|
Source code: https://github.com/mrdulin/mocha-chai-sinon-codelab/tree/master/src/stackoverflow/59435659