如何用Sinon.js监视与被测函数在同一js文件中的函数

How to spy a function with Sinon.js that is in the same js file as the function under test

本文关键字:函数 js 文件 Sinon 何用 监视      更新时间:2023-09-26

我有一个Sinon.js的问题,而试图窥探一个函数是在相同的javascript文件作为我想测试的函数。此外,我断言被监视的函数只被调用一次。不幸的是,测试失败了。有趣的是,如果被监视的函数在另一个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

two.js:

var second = function(){
  console.log('two: second')
}
module.exports.second = second

我在网上找不到任何有用的东西,我也尝试了不同的东西。请帮帮我,我遗漏了什么?

干杯诺亚

不幸的是,测试失败了

这是因为mock_test.js中的one.some_method()在闭包中调用another_method, one.some_method()持有one.js中的内容,而不是mock_test.js中的one.another_method

举例说明

让我们把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被记录到控制台,因为foo中的console.log(a)指向闭包中的var a, foo持有one.js的内容。

Diana被记录到控制台,因为foo中的console.log(this.b)指向mock_test.js中的one.b

那么你需要做些什么来使它工作呢?

你需要修改:

var some_method = function(){
  console.log('one: some method')
  another_method()
}

:

var some_method = function(){
  console.log('one: some method')
  this.another_method()
}