如何使用 jasmine-node 监视依赖模块内的方法

How to spy on a method inside a dependent module using jasmine-node

我正在尝试为一个模块(比如模块 A)编写 jasmine 测试,'requires' 另一个模块(模块 B)。

======> moduleB.js

function moduleBFunction(){
   console.log('function inside moduleB is called');
}

======> moduleA.js

var moduleB = require('./moduleB');
function moduleAfunction(input){
   if(input){
      moduleB.moduleBFunction()
   }

}

我想编写一个 jasmine 测试用例来测试我调用 moduleAfunction 时是否调用 moduleBfunction。我尝试使用 spyOn() 编写测试。但我不确定如何模拟依赖模块中的方法。我做了一些研究,发现我可以使用 'rewire' 模块来达到这个目的,如下所示

var moduleB = require('../moduleB');
moduleB.__set__('moduleBfunction', moduleBfunctionSpy);
moduleA.__set__('moduleB', moduleB);
it('should call moduleBfunction', function(){
    moduleA.moduleAfunction()
    expect(moduleB.moduleBfunction()).toHaveBeenCalled()
});

但我觉得应该有更简单的方法。

求推荐。

我推荐sinon.js

var sinon = require('sinon')
var moduleA = require('../moduleA')
var moduleB = require('../moduleB')


it('should call moduleBfunction', function() {
  var stub = sinon.stub(moduleB, 'moduleBfunction').returns()
  moduleA.moduleAfunction()
  expect(moduleB.moduleBfunction.calledOnce)
  stub.restore()
})

您可以轻松伪造许多不同的行为,例如:

  • 存根抛出
  • 存根returns某个值
  • stub yields(模拟异步回调)
  • stub 的工作仅限于某些输入参数

不要忘记在执行下一个测试之前恢复每个存根。最好使用沙箱和 afterEach / beforeEach

describe('tests which require some fakes', function() {
  var sandbox

  beforeEach(function() {
    sandbox = sinon.sandbox.create()
  })

  afterEach(function() {
    sandbox.restore()
  })
})