我有一个依赖于另一个函数的函数,而不是测试依赖关系,我只想测试依赖函数的特定结果。然而,当我存根函数时,什么都不会发生,返回的结果就好像我从来没有存根函数一样。
示例代码:
// File being tested
function a() {
let str = 'test';
return b(str);
}
function b(str) {
return str + str;
}
module.exports = {
a: a,
b: b
};
// Test file
let test = require('file.to.test.js');
it('should correctly stub the b function', () => {
sinon.stub(test, 'b').returns('asdf');
let result = test.a();
// Expected
assert(result === 'asdf');
// Received
assert(result === 'testtest');
});
您的存根没有预期的效果,因为您已经存根了导入对象的属性。但是,函数 a()
继续调用原始函数 b()
,因为它调用函数,而不是对象方法。
如果您将代码更改为具有属性< code>b和< code>a的对象,并且属性< code>a调用属性< code>b,那么它将按预期方式工作:
const x = {};
x.a = () => {
let str = 'test';
return x.b(str);
}
x.b = (str) => {
return str + str;
}
module.exports = x;
另外,看看这个答案,它描述了类似的问题。