有时,在一个模块中,函数会调用其他函数(用于因式分解、代码抽象等),我们可能希望在不测试内部函数的情况下测试调用者函数。
但是,此代码不能按原样工作:
// src/my-module.js
function externalFunction() {
return internalFunction();
}
function internalFunction() {
return { omg: 'this is real' };
}
module.exports = {
externalFunction,
};
// test/my-module.spec.js
const { assert } = require('chai');
const {
describe,
it,
before,
beforeEach,
} = require('mocha');
const sinon = require('sinon');
let myModule;
describe('externalFunction', () => {
before(() => {
myModule = require('../src/my-module');
});
beforeEach(() => {
// partial stubbing not working
sinon.stub(myModule, 'internalFunction').callsFake(() => ({ omg: 'this is fake' }));
})
it('returns the result of internalFunction', () => { // FAILING
const result = myModule.externalFunction();
assert.deepEqual(result, { omg: 'this is fake' });
});
});