如何为多个mocha chai-http测试文件启动服务器?

时间:2015-03-16 19:05:20

标签: node.js testing sails.js mocha chai

我在我的mocha chai-http测试中在我之前的块中启动了我的节点服务器。

我让它适用于单个测试文件。但是,当我尝试在单个命令NODE_ENV=test mocha test/**/*.js中运行多个测试时,我收到错误。

我尝试在每个测试文件的不同端口上启动节点服务器。这没有用,导致节点服务器启动错误。

我现在认为如果我能在我的其他测试文件之前运行一个mocha文件来启动服务器然后在其他测试文件之后运行的单个文件来杀死/停止服务器

我将如何解决这个问题。

以下是我的一些代码:

以下是我的测试文件之一供参考:

var chai = require('chai');
var chaiHttp = require('chai-http');
chai.use(chaiHttp);
var expect = chai.expect;
var Sails = require('sails');

describe('REST User API', function() {

  var app;    // for access to the http app
  var sails;  // for starting and stopping the sails server

  before(function (done) {
    Sails.lift({
      port: 3001,
      log: {
        level: 'error'
      }
    }, function (_err, _sails) {
      if(_err){
        console.log("Error!", _err);
        done();
      }
      else {
        app = _sails.hooks.http.app;
        sails = _sails;
        done();
      }
    });
  });

  describe("user session", function () {
    var res;  // http response
    var authenticatedUser;

    before(function (done) {
      chai.request(app)
        .post('/users/signin')
        .set('Accept', 'application/json')
        .set('Content-Type', 'application/json')
        .send({ email: 'admin@test.com', password: 'secret'})
        .end(function (_res) {
          res = _res; // Record the response for the tests.
          authenticatedUser = JSON.parse(_res.text); // Save the response user for authenticated tests
          done();
        });
    });

    it("should connect with a 200 status", function () {
      expect(res).to.have.status(200);
    });

    it("should have a complete user session", function () {
      var userSession = authenticatedUser;
      expect(userSession).to.have.property('firstName');
      expect(userSession).to.have.property('lastName');
      expect(userSession).to.have.property('gender');
      expect(userSession).to.have.property('locale');
      expect(userSession).to.have.property('timezone');
      expect(userSession).to.have.property('picture');
      expect(userSession).to.have.property('phone');
      expect(userSession).to.have.property('email');
      expect(userSession).to.have.property('username');
      expect(userSession).to.have.property('confirmed');
      expect(userSession).to.have.property('status');
      expect(userSession).to.have.property('authToken');
    });

  });

  after(function (done) {
    sails.lower(function() {
      done()
    });
  });

});

1 个答案:

答案 0 :(得分:0)

从 mocha v8.2.0,您可以使用 GLOBAL FIXTURES 为所有测试套件设置和拆除您的网络服务器。全局装置保证只执行一次。

相关问题