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