【发布时间】:2019-07-28 15:21:27
【问题描述】:
假设您在模块 myModule 中有一个名为 myMethod 的方法,如下所示:
function myMethod() {
return 5;
}
module.exports.myMethod = myMethod;
现在如果我想用 Sinon 存根这个方法返回 2 而不是 5 我会写
const myModule = require('path/myModule');
sinon.stub(myModule, 'myMethod').returns(2);
现在在你实际调用方法的地方,你碰巧通过对象销毁导入了这样的方法
const { myMethod } = require('path/myModule');
console.log(myMethod()); // Will print 5
如果你这样做,myMethod 实际上不会被存根,并且不会返回 2 而是 5。
如果您再次需要该模块并使用所需模块中的功能,它将起作用
const myModule= require('path/myModule');
console.log(myModule.myMethod()); // Will print 2
除了改变我导入函数的方式之外,还有其他人对此有解决方案吗?
【问题讨论】: