[英]Sinon stub not properly replacing stubbed function
我有一个依赖于另一个函数的函数,而不是测试依赖关系,我只想测试该依赖关系函数的特定结果。 但是,当我对函数进行存根操作时,什么也没有发生,并且返回结果就好像我从来没有对函数进行存根一样。
示例代码:
// 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');
});
存根没有预期的效果,因为您已存根导入对象的属性。 但是, function a()
继续调用原始function b()
,因为它调用的是函数,而不是对象方法。
如果更改代码的方式是存在具有属性b
和a
的对象,而属性a
调用属性b
,则它将按预期的方式工作:
const x = {};
x.a = () => {
let str = 'test';
return x.b(str);
}
x.b = (str) => {
return str + str;
}
module.exports = x;
另外,看看这个答案 ,它描述了类似的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.