npm 运行 脚本:节点 server.js && mocha 测试

npm run script: node server.js && mocha test

我的用例非常简单:

首先我想 运行 node server.js(启动我的 Node.js 应用程序)- Node 启动后 - 我想 运行 mocha test(运行对之前 server.js 提供的 API 进行一些测试)通过执行 npm run test

脚本:"test": "NODE_ENV=development node server.js && mocha test"

节点启动,可惜mocha test好像没有执行:

那么如何在node server.js之后执行mocha test

你之所以 运行 这样做是因为 node server.js 连续 运行s 直到被杀死 (Ctrl + C) 或发生致命的未处理异常。由于 node 进程保持 运行ning mocha test 永远不会被执行。

一种方法是使用 gulp as a task runner and utilize tasks implementing gulp-nodemon and gulp-mocha。如果您以前从未使用过 Gulp 或者不熟悉任务 运行 人员,我建议您事先阅读文档以了解其工作原理。

将下面的 gulpfile.js 添加到您的应用程序(根据需要调整一些设置)并使用下面的 test 脚本修改您的 package.json 脚本,这应该可以解决您的问题。

gulpfile.js

var gulp = require('gulp');
var mocha = require('gulp-mocha');
var nodemon = require('gulp-nodemon');

gulp.task('nodemon', (cb) => {
  let started = false;

  return nodemon({
    script: 'server.js'
  })
    .on('start', () => {
      if (!started) {
        started = true;
        return cb();
      }
    })
    .on('restart', () => {
      console.log('restarting');
    });

});

gulp.task('test', ['nodemon'], function() {
  return gulp.src('./test/*.js')
    .pipe(mocha({reporter: 'spec' }))  
    once('error', function() {
        process.exit(1);
    })
    .once('end', function() {
      process.exit();
    });
});

package.json scripts

{
  "scripts": {
    "test": "NODE_ENV=development gulp test"
  }
}

超级测试选择

一个更优雅的解决方案,在我看来也是更好的选择,是重写您的测试以使用 supertest。基本上,你对 supertest 所做的就是将你的 Express 实例传递给它,然后 运行 断言使用 supertest 包对其进行测试。

var mocha = require('mocha');
var request = require('supertest');
var server = require('server');

describe('test server.js', function() {

    it('test GET /', function(done) {
        request(server)
            .get('/')
            .expect(200, done);
    });

});

将此代码添加到您的测试用例中

after(function (done) {
        done();
       process.exit(1);
 })