如何在运行测试套件时仅启动/停止一次NodeJS服务器

Hoa*_*yen 3 mocha.js node.js selenium-webdriver sails.js webdriver-io

我正在为NodeJS编写selenium测试套件.这是一个示例测试文件:

var Sails = require('sails');

// create a variable to hold the instantiated sails server
var app;
var client;

// Global before hook
before(function(done) {

  // Lift Sails and start the server
  Sails.lift({
    log: {
      level: 'error'
    },
    environment: 'test',
    port: 1338
  }, function(err, sails) {
    app = sails;
    done(err, sails);
  });
});

// Global after hook
after(function(done) {
  app.lower(done);
});

beforeEach(function(done) {
  client = require('webdriverjs').remote({desiredCapabilities:{browserName:'chrome'}});
  client.init(done);
});

afterEach(function(done) {
  client.end(done);
});

describe("Go to home page", function() {
  it('should work', function(done) {
    client
      .url('http://localhost:1338/')
      .pause(5000)
      .call(done);
  });
});
Run Code Online (Sandbox Code Playgroud)

目前:

  • 启动每个测试文件,它会启动Sails服务器
  • 完成每个测试文件后,它会关闭Sails服务器
  • 启动每个测试,它会启动浏览器
  • 完成每个测试后,它会关闭浏览器

因此,如果我有10个selenium测试文件,它将启动/关闭Sails服务器10次.有没有办法只启动Sails服务器一次,运行所有测试文件,然后关闭它?

我正在使用Sails + Mocha + webdriverjs堆栈.这是我的Makefile配置

test:
    @./node_modules/.bin/mocha -u bdd -R spec --recursive --timeout 15000
.PHONY: test
Run Code Online (Sandbox Code Playgroud)

dyl*_*nts 5

一种可能的解决方案是切换到使用npm test,将测试执行行存储在package.json文件中,然后利用脚本pretestposttest脚本阶段.在这些命令中,您可以执行一个脚本,该脚本将启动您的服务器(startSailsServer.js),并分别关闭您的服务器.然后,您可以在每个测试文件中取出服务器的启动和停止.

所以你package.json会有类似的东西(你必须将启动/停止sails服务器逻辑移动到这些startSailsServer.jsstopSailsServer.js文件):

"scripts": {
    "pretest": "node startSailsServer.js",
    "test": "./node_modules/.bin/mocha -u bdd -R spec --recursive --timeout 15000",
    "posttest": "node stopSailsServer.js"
}
Run Code Online (Sandbox Code Playgroud)

然后运行测试,你会执行 npm test