当我尝试监视与我要测试的函数位于同一 javascript 文件中的函数时,我遇到了 Sinon.js 问题。此外,我断言 sied 函数被调用一次。不幸的是测试失败了。有趣的是,如果被监视的函数位于另一个 javascript 文件中而不是被测试的函数中,那么它就可以工作!
这是我的代码:
mock_test.js:
var sinon = require('sinon')
var one = require('./one.js')
var two = require('./two.js')
describe('Spy ', function () {
it('Spy another method', sinon.test(function (done) {
var another_method_spy = sinon.spy(one, 'another_method')
one.some_method()
sinon.assert.calledOnce(another_method_spy)
done()
}))
it('Spy second method', sinon.test(function (done) {
var second_method = sinon.spy(two, 'second')
one.call_second()
sinon.assert.calledOnce(second_method)
done()
}))
})
one.js:
var two = require('./two.js')
var some_method = function(){
console.log('one: some method')
another_method()
}
var another_method = function(){
console.log('one: another method')
}
var call_second = function(){
console.log('one: call second')
two.second()
}
module.exports.some_method = some_method
module.exports.another_method = another_method
module.exports.call_second = call_second
两个.js:
var second = function(){
console.log('two: second')
}
module.exports.second = second
我在互联网上找不到任何有用的东西,而且我也尝试了不同的方法。请帮忙,我在这里缺少什么?
干杯 诺亚
最佳答案
Unfortunately the test fails
那是因为one.some_method()
在 mock_test.js 中调用 another_method
封口内 one.some_method()
保留了 one.js 的内容,而不是 one.another_method
在mock_test.js中。
举例说明
让我们将 one.js 重写为:
var a = 'I am exported';
var b = 'I am not exported';
function foo () {
console.log(a);
console.log(this.b)
}
module.exports.a=a;
module.exports.foo=foo;
和mock_test.js:
var one = require('./one');
console.log(one); // { a: 'I am exported', foo: [Function: foo] }
one.a = 'Charles';
one.b = 'Diana';
console.log(one); // { a: 'Charles', foo: [Function: foo], b: 'Diana' }
现在如果我们调用one.foo()
这将导致:
I am exported
Diana
I am exported
被记录到控制台,因为 console.log(a)
里面foo
指向var a
封口内 foo
持有 one.js 的内容。
Diana
被记录到控制台,因为 console.log(this.b)
里面foo
指向one.b
在mock_test.js中。
那么您需要做什么才能使其正常工作?
您需要更改:
var some_method = function(){
console.log('one: some method')
another_method()
}
至:
var some_method = function(){
console.log('one: some method')
this.another_method()
}
关于javascript - 如何使用与被测函数位于同一js文件中的Sinon.js来监视函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40660832/