当使用对象销毁时,Sinon存根似乎不起作用

问题描述 投票:0回答:2

假设你在模块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

除了改变我导入函数的方式之外,有没有人能解决这个问题?

node.js sinon
2个回答
1
投票

存根的myMethod将具有与原始方法不同的参考。在解构示例中,您将在可以存根之前设置引用。

// cannot be stubbed
const { myMethod } = require('path/myModule');

// can be stubbed
const myModule = require('path/myModule');
myModule.myMethod();

有关详细信息,请查看this的相似问题


0
投票

这个有可能。

请注意,一旦运行:

const { myMethod } = require('./lib');

......它会记住当时的myMethod

因此,您必须确保在该代码运行之前设置存根。


所以对于这个lib.js

function myMethod() {
  return 5;
}
module.exports.myMethod = myMethod;

这个code.js

const { myMethod } = require('./lib');
console.log(myMethod());

你只需要这样做:

const sinon = require('sinon');

const myModule = require('./lib');
sinon.stub(myModule, 'myMethod').returns(2);  // set up the stub FIRST...
require('./code');  // ...THEN require the code (prints "2")
© www.soinside.com 2019 - 2024. All rights reserved.