从同一个模块调用存根模块功能 [英] Stub module function called from the same module
问题描述
我想不出一种方法来对从定义此函数的同一模块中调用的函数进行存根(存根似乎不起作用).这是一个示例:
I can't figure out a way to stub a function called from within the same module this function is defined (the stub does not seem to work). Here's an example:
myModule.js:
myModule.js:
'use strict'
function foo () {
return 'foo'
}
exports.foo = foo
function bar () {
return foo()
}
exports.bar = bar
myModule.test.js:
myModule.test.js:
'use strict'
const chai = require('chai')
const sinon = require('sinon')
chai.should()
const myModule = require('./myModule')
describe('myModule', () => {
describe('bar', () => {
it('should return foo', () => {
myModule.bar().should.equal('foo') // succeeds
})
describe('when stubbed', () => {
before(() => {
sinon.stub(myModule, 'foo').returns('foo2') // this stub seems ignored
})
it('should return foo2', () => {
myModule.bar().should.equal('foo2') // fails
})
})
})
})
这让我想起了(几乎)不可插拔的Java静态函数.
This reminds me of Java static functions which are not stubbable (almost).
有什么想法可以实现我想要做的事情吗?我知道在另一个模块中提取foo
是可以的,但这不是我要在这里执行的操作.我还知道在bar
方法中使用关键字this
调用foo
也是可行的,我很困惑在这种情况下使用̀ this
(因为我没有使用OOP)
Any idea how to achieve what I'm trying to do? I know that extracting foo
in a different module will work, but that's not what I'm trying to do here. I'm also aware that invoking foo
in the bar
method with the keyword this
will also work, I'm puzzled toward the use of ̀this
in this context (since I'm not using OOP).
推荐答案
我刚刚对此进行了测试.它就像魅力一样.
I just tested this. And it works like charm.
'use strict'
function foo () {
return 'foo';
}
exports.foo = foo;
function bar () {
return exports.foo(); // <--- notice
}
exports.bar = bar;
说明
当您执行sinon.stub(myModule, 'foo').returns('foo2')
时,sinon
将从myModule.js
内部对exported
对象的foo
而不是实际的foo
函数进行存根...正如您必须知道的那样,可以从以下位置访问foo
在模块外部.因此,当您设置exports.foo
时,导出的对象exports.foo
将存储foo
的引用.并且当您呼叫sinon.stub(myModule, 'foo').returns('foo2')
时,sinon
将存根exports.foo
而不是实际的foo
when you do sinon.stub(myModule, 'foo').returns('foo2')
then sinon
stubs the exported
object's foo
not the actually foo
function from inside your myModule.js
... as you must know, foo
is in accessible from outside the module. So when you set exports.foo
, the exported object exports.foo
stores the ref of foo
. and when you call sinon.stub(myModule, 'foo').returns('foo2')
, sinon
will stub exports.foo
and not the actual foo
希望这很有道理!
这篇关于从同一个模块调用存根模块功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!