2016-01-13 67 views
0

我有下面的代碼的文件config.js它:如何存根對象的屬性,而不是方法?

module.exports: 
{ 
    development: { 
     switch: false 
     } 
} 

我有下面的代碼的另一個文件bus.js它:

var config=require('config.js'); 

getBusiness:function(req,callback){ 
     if(config.switch) { 
        // Do something 
     }else{ 
       // Do something else 
     } 
} 

現在,我想單元測試文件bus.js

require('mocha'); 

var chai = require('chai'), 
     expect = chai.expect, 
     proxyquire = require('proxyquire'); 

var bus = proxyquire('bus.js', { 
       'config':{ 
         switch:true 
        } 
}); 

describe('Unit Test', function() { 

     it('should stub the config.switch', function(done) { 
      bus.getBusiness(req, function(data) { 
       // It should stub the config.switch with true not false and give code coverage for if-else statmt. 
      }); 
      done(); 
     }); 
}); 

任何建議或幫助......

+0

所以......這是行不通的? (如果你修復了報價錯字。)會發生什麼?任何錯誤? –

+0

@ T.J. Crowder當我在測試中使用console.log(config.switch)時,它給了我null或undefined。 – Prajwal

+0

@ T.J.Crowder測試案例給了我bus.js其他部分的代碼覆蓋。 – Prajwal

回答

1

您需要REQ像這樣使用你的模塊var config=require('./config.js');

編輯:你應該改變你的要求呼叫以上。即使它代理爲('config.js'),它在現實生活中也不起作用。你也可能需要以相同的方式調用總線,並像實際文件中那樣構建配置對象。

var bus = proxyquire('./bus.js', { 
      './config':{ 
       development: {     
        switch:true 
       } 
       } 
}); 
+0

我在測試文件中調用了'config'模塊。 ,有沒有什麼辦法可以覆蓋原配置的屬性值與我分配給它的任何值,並使用它進行測試? – Prajwal

+0

我無法提供值 – Prajwal

+0

工作...感謝隊友... – Prajwal

1

在我看來,你可以在你的測試文件這樣做:

var chai = require('chai'), 
    expect = chai.expect; 
var config = require('./config'); 

describe('Unit Test', function() { 

    it('should stub the config.switch', function(done) { 
    config.development.switch = true; 
    bus.getBusiness(req, function(data) { 
     ... 
     done(); 
    }); 
    }); 

}); 
相關問題