我正在单元测试一个特定的方法,并且在模拟过程中调用的另一个函数时遇到问题。在我的例子中,要测试的方法是在一个类中定义的,而我想要模拟的函数是在一个子模块中定义的。如何模拟此函数?请参阅下面的代码。
在过去,我曾使用Sinon包模拟/存根依赖项(示例(。但这在这种情况下不起作用。这是我第一次测试类中定义的方法,所以也许这就是嘲笑依赖关系不起作用的原因。
我的代码
包含测试函数的模块(myLib/myDir/commo.js(
const { externalFunction } = require('./external-function')
class Combo {
constructor(props) {}
async myMethod () {// The function under test.
externalFunction()
}
}
const myCombo = props => new Combo(props)
module.exports = { myCombo }
我的测试文件(Test/myLib/myDir/commo.Test.js(;没有嘲笑的尝试
const { myCombo } = require('../../../myLib/myDir/combo')
const comboObj = myCombo({}) // Instantiate object to expose method to test.
await comboObj.myMethod()// Call method that I want to test. This throws type error because myMethod function calls externalFunction, which throws an error in the test environment.
我的测试文件(Test/myLib/myDir/commo.Test.js(;尝试使用Sinon软件包模拟
const sinon = require('sinon')
const dependencyModule = require('./external-function')// Defines the method dependencyModule.methodToMock
const myStub = sinon.stub(dependencyModule, 'methodToMock').returns(555) // Stubs dependencyModule.methodToMock and ensures it always returns the value: 555.
const comboObj = myCombo({}) // Instantiate object to expose method to test.
await comboObj.myMethod()// Call method that I want to test. This throws type error because myMethod function calls externalFunction, which throws an error in the test environment.
如何你需要遵循"无法销毁存根模块"在官方指南上如何截断模块的依赖关系
例如我在同一目录下有external-function.js、combo.js和test.js文件。我选择使用console.log来显示stub是否工作,并调用伪函数,因为您不希望在myMethod上返回什么。
// File: external-function.js
function externalFunction () {
console.log('Original Called');
}
module.exports = { externalFunction };
// File: combo.js
// Note: "stubbed module can not be destructured."
const externalFunction = require('./external-function')
class Combo {
constructor(props) {}
async myMethod () {
externalFunction.externalFunction()
}
}
const myCombo = props => new Combo(props)
module.exports = { myCombo };
// File: test.js
const sinon = require('sinon');
const { myCombo } = require('./combo');
const dependencyModule = require('./external-function');
describe('myCombo', () => {
it('myMethod', async () => {
sinon.stub(dependencyModule, 'externalFunction').callsFake(() => {
console.log('Fake Called');
});
const comboObj = myCombo({});
await comboObj.myMethod();
});
});
当我在我的终端上使用nyc和摩卡运行它时:
$ npx nyc mocha test.js
myCombo
Fake Called
✓ myMethod
1 passing (3ms)
----------------------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------------------|---------|----------|---------|---------|-------------------
All files | 85.71 | 100 | 75 | 83.33 |
combo.js | 100 | 100 | 100 | 100 |
external-function.js | 50 | 100 | 0 | 50 | 2
----------------------|---------|----------|---------|---------|-------------------