2016-09-02 28 views
1

我有一個共同的測試,我想在多個測試文件都跑測試,我做了一些研究,這是建議的解決方案,我發現有一個文件測試:摩卡/椅 - 在多個文件中

目錄結構:

|--test 
    |--common 
     |--common.js 
    |--common_functions.js 
    |--helpers.js 
    |--registration.js 

common.js

var helpers = require("../../services/helpers"); 
var chai = require("chai"); 
var expect = require("chai").expect; 
chai.should(); 
chai.use(require("chai-things")); 
var testData = require("../../config/testData"); 

    it('check if we are connected to local test db', function(done) { 
     helpers.checkTestDB(function(err, result) { 
      expect(err).to.equal(null); 
      result.should.equal('This is the test DB'); 
      done(); 
     }); 
    }); 

個common_functions.js

exports.importTest = function(name, path) { 
    describe(name, function() { 
     require(path); 
    }); 
} 

helpers.js/registration.js

... 
var common_functions = require('./common_functions'); 
... 
describe("Common Tests Import", function(){ 
    common_functions.importTest("checkDb",'./common/common'); 
}); 

的問題是,測試只能運行在這兩個文件中的一個,如果我留在這兩者運行在助手上,如果我註釋掉助手,註冊運行,是否有辦法在每個助手中運行它?

原因是我在每個文件中設置env變量以使用測試數據庫,但是有很多事情要做,並且萬一它以某種方式更改,我希望它在單獨的文件上運行。

回答

1

您需要類似於您在common_functions.js做了什麼common.js事做:出口調用it,而不是讓it坐在頂層喜歡你現在要做的一個功能。因此,修改common.js到這樣的事情:

var helpers = require("../../services/helpers"); 
var chai = require("chai"); 
var expect = require("chai").expect; 
chai.should(); 
chai.use(require("chai-things")); 
var testData = require("../../config/testData"); 

module.exports = function() { 
    it('check if we are connected to local test db', function(done) { 
     helpers.checkTestDB(function(err, result) { 
      expect(err).to.equal(null); 
      result.should.equal('This is the test DB'); 
      done(); 
     }); 
    }); 
}; 

然後你導入模塊後調用此函數。所以更改common_functions.js到這樣的事情:

exports.importTest = function(name, path) { 
    describe(name, function() { 
     // We call the function exported by the module. 
     require(path)(); 
    }); 
} 

否則,問題是,由於CommonJS的模塊是單身,那麼it呼叫common.js將被執行一次,只有一次,當節點讀取該文件,在內存中創建模塊。隨後的require('./common/common')調用將不會再次執行模塊的代碼。