7
我找不到一种方法来存储从同一个模块中调用的函数,该函数被定义(存根似乎不起作用)。这里有一个例子:从同一个模块调用的存根模块功能
myModule.js:
'use strict'
function foo() {
return 'foo'
}
exports.foo = foo
function bar() {
return foo()
}
exports.bar = bar
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静态功能,这是不是stubbable(几乎)。
任何想法如何实现我想要做的?我知道在不同的模块中提取foo
会起作用,但这不是我在这里要做的。我也知道在bar
方法中使用关键字this
调用foo
也是可行的,我很困惑在这种情况下使用this
(因为我没有使用OOP)。
太好了,谢谢。使用'exports'仍然有点难看,因为它有点像'this'完成同样的工作,但是会做。在静态环境中使用'this'使我的脑海中的某些东西难以理解。 – Simon
非常欢迎我的朋友! –
如果您无法更改源代码,该怎么办? – nbkhope