2016-04-23 15 views
0

比方說,我有一個出口這樣的模塊:爲什麼不讓sinon認出我的存根?

module.exports = mymodule; 

然後在我的測試文件,我需要的模塊和存根它。

var mymodule = require('./mymodule'); 

describe('Job gets sports data from API', function(){ 

    context('When there is a GET request', function(){ 
     it('will call callback after getting response', sinon.test(function(done){ 
      var getRequest = sinon.stub(mymodule, 'getSports'); 
      getRequest.yields(); 
      var callback = sinon.spy(); 
      mymodule.getSports(callback); 
      sinon.assert.calledOnce(callback); 
      done(); 
     })); 
    }); 
}); 

工作和測試通過!但是如果我需要導出多個對象,一切都會崩潰。請看下圖:

module.exports = { 
    api: getSports, 
    other: other 
}; 

然後我儘量調整我的測試代碼:

var mymodule = require('./mymodule'); 

describe('Job gets sports data from API', function(){ 

    context('When there is a GET request', function(){ 
     it('will call callback after getting response', sinon.test(function(done){ 
      var getRequest = sinon.stub(mymodule.api, 'getSports'); 
      getRequest.yields(); 
      var callback = sinon.spy(); 
      mymodule.api.getSports(callback); 
      sinon.assert.calledOnce(callback); 
      done(); 
     })); 
    }); 
}); 

在這種情況下,我的測試胡扯出來。我怎樣才能改變我的存根代碼工作?謝謝!在此基礎上

module.exports = { 
    api: getSports, 
    other: other 
}; 

它看起來像mymodule.api

回答

1

本身並不具有getSports方法。相反,mymodyle.api是對模塊內部功能getSports的引用。

相反磕碰getSports,你會需要存根api

var getRequest = sinon.stub(mymodule, 'api'); 

然而,鑑於你是如何想存根getSports,你可能反而要更新你如何導出函數,而不是如何正在扼殺它。