簡體   English   中英

如何使用茉莉花節點監視依賴模塊中的方法

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

我正在嘗試為模塊“(說”模塊A)“需要”另一個模塊(“模塊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()
   }

}

我想編寫一個茉莉花測試用例,在我調用moduleAfunction時進行測試,是否調用moduleBfunction。 我試圖使用spyOn()編寫測試。 但是我不確定如何在依賴模塊中模擬方法。 我做了一些研究,發現我可以為此目的使用“重新接線”模塊,如下所示

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()
})

您可以輕松地偽造許多不同的行為,例如:

  • 存根拋出
  • 存根返回某個值
  • 存根收益 (模仿異步回調)
  • 存根僅適用於某些輸入參數

在執行下一個測試之前,請不要忘記還原每個存根。 最好使用沙盒和afterEach / beforeEach

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

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM