Mocha / Chair - 在多个文件中运行测试

时间:2016-09-02 18:01:22

标签: unit-testing mocha chai

我有一个常见的测试我想在多个测试文件中运行,我做了一些研究,这是我发现在一个文件中包含测试的建议解决方案:

目录结构:

|--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 个答案:

答案 0 :(得分:1)

你需要common.js类似于你在common_functions.js中所做的事情: export 一个调用it的函数,而不是{{1}像你现在一样坐在顶层。因此,将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

否则,问题在于因为CommonJS模块是单例,所以exports.importTest = function(name, path) { describe(name, function () { // We call the function exported by the module. require(path)(); }); } 中的it调用将执行一次,只执行一次,当Node读取文件时并在内存中创建模块。后续common.js次调用将不再执行模块的代码。

相关问题