Loopback 和 mocha:等待服务器完成启动脚本

Loopback and mocha: wait for server to finish boot scripts

您好,就问题标题而言,我想知道如何在启动测试之前检查环回引导脚本是否已完成。 在示例项目中:

https://github.com/strongloop/loopback-example-relations

测试文件夹中有一个 file 似乎可以解决问题,但不幸的是它没有解决问题。

start-server.js:

var app = require('../server/server');

module.exports = function(done) {
  if (app.loaded) {
    app.once('started', done);
    app.start();
  } else {
    app.once('loaded', function() {
      app.once('started', done);
      app.start();
    });
  }
};

此脚本在rest test api中加载如下:

before(function(done) {
    require('./start-server');
    done();
});

但该函数从未被调用。这是使用该脚本的正确方法吗?

我以以下实现结束:

before(function (done) {
    if (app.booting) {
        console.log('Waiting for app boot...');
        app.on('booted', done);
    } else {
        done();
    }
});

这有效,但我对那个 start-server 脚本感到困惑。

编辑 按照@stalin 的建议,我修改了 before 函数,如下所示:

before(function(done) {
    require('./start-server')(done);
});

并在 else 分支中执行,但从未调用 done

您永远不会将 done 函数传递给 start-server 脚本。尝试这样做:

before(function(done) {
    var server = require('./start-server');
    server(done);
});

当您的启动脚本使用异步函数(例如自动迁移模型架构)时,它可能不起作用。应用程序将设置 booting = false 并且不会等待回调完成,直到您显式调用回调:

// boot script with extra callback param:
module.exports = function (app, cb) {
  var db = app.dataSources.db;

  // update all database models
  db.autoupdate(function (err) {
    if (err) throw err;
    cb();
  });
};

我只想指出 Loopback 团队的做法

https://github.com/strongloop/loopback/blob/44951a1032d2115a20a098fbeea767e0a5cd72c1/test/helpers/loopback-testing-helper.js#L39

beforeEach(function(done) {
    this.app = app;
    var _request = this.request = request(app);
    this.post = _request.post;
    this.get = _request.get;
    this.put = _request.put;
    this.del = _request.del;
    this.patch = _request.patch;

    if (app.booting) {
      return app.once('booted', done);
    }
done();

然后您会发现他们几乎在每个集成测试中都在调用它

https://github.com/strongloop/loopback/blob/b77907ffa59c7031fcb3bb6dbff96894bc597ba4/test/user.integration.js#L16

describe('access control - integration', function() {
  lt.beforeEach.withApp(app);