问题描述
我正在对特定方法进行单元测试,并且在模拟在此过程中调用的另一个函数时遇到问题。在我的例子中,要测试的方法是在一个类中定义的,而我想要模拟的函数是在一个单独的模块中定义的。我如何模拟这个功能?请参阅下面的代码。
过去,我使用 Sinon 包来模拟/存根依赖项 (example)。但这在这种情况下不起作用。这是我第一次测试类中定义的方法,所以也许这就是模拟依赖项不起作用的原因。
我的代码
包含测试功能的模块 (myLib/myDir/combo.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/combo.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/combo.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.
解决方法
如何?您需要遵循“无法解构存根模块”。在官方指南How to stub a dependency of a module
例如我在同一个目录下有文件 external-function.js、combo.js 和 test.js。我选择使用 console.log 来显示存根工作并调用了假函数,因为您不期望在 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 和 mocha 运行它时:
$ 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
----------------------|---------|----------|---------|---------|-------------------