简体   繁体   English

GitLab-CI和node.js - 如何启动本地服务器然后运行测试?

[英]GitLab-CI and node.js - how to start a local server then run tests?

I've set up GitLab-CI, and am writing my .gitlab-ci.yml to run my tests. 我已经设置了GitLab-CI,并且正在编写我的.gitlab-ci.yml来运行我的测试。 My app is written in node.js, and the file looks like this: 我的应用程序是用node.js编写的,文件如下所示:

before_script:
  - npm install
  - node server.js

stages:
  - test

job_name:
  stage: test
  script:
    - npm run test

I'm having trouble actually starting the server then running tests, as node server.js creates a foreground process that never exists unless you do so manually. 我在启动服务器然后运行测试时遇到了麻烦,因为node server.js会创建一个从不存在的前台进程,除非您手动执行此操作。 Is there a way to start the server, then move on, then stop it once the tests have finished? 有没有办法启动服务器,然后继续前进,然后在测试完成后停止它?

Or am I actually doing this wrong, and should my server get started in the tests themselves? 或者我实际上做错了,我的服务器应该自己开始测试吗? Everything I read just says "start node then in another terminal run your tests against your local server" but this is obviously pointless in an automated CI system? 我读到的所有内容都说“启动节点然后在另一个终端上运行您的本地服务器测试”但这在自动CI系统中显然毫无意义?

I have the exact same setup, with gitlab-ci docker runner. 我有完全相同的设置,使用gitlab-ci docker runner。 You don't need to launch the node server.js before launching your tests, you can let your test runner handle it. 在启动测试之前,您不需要启动node server.js ,您可以让测试运行器处理它。 I use Mocha + Chai (with chai-http). 我使用Mocha + Chai(带chai-http)。 You can also use supertest to do the same. 您也可以使用supertest来做同样的事情。

It look for available ports before each test so you don't end up with conflicting port. 它在每次测试之前查找可用端口,因此您不会遇到冲突的端口。

Here is how it looks : 以下是它的外观:

var chai = require('chai');
var chaiHttp = require('chai-http');
// Interesting part
var app = require('../server/server');
var loginUser = require('./login.js');
var auth = {token: ''};

chai.use(chaiHttp);
chai.should();

describe('/users', function() {

  beforeEach(function(done) {
    loginUser(auth, done);
  });

  it('returns users as JSON', function(done) {
    // This is what launch the server
    chai.request(app)
    .get('/api/users')
    .set('Authorization', auth.token)
    .then(function (res) {
      res.should.have.status(200);
      res.should.be.json;
      res.body.should.be.instanceof(Array).and.have.length(1);
      res.body[0].should.have.property('username').equal('admin');
      done();
    })
    .catch(function (err) {
      return done(err);
    });
  });
});

Alternatively, you can use nohup command to launch your server in background. 或者,您可以使用nohup命令在后台启动服务器。

$ nohup node server.js &

( & at the end of line is used to return to the prompt) &在行尾用于返回提示)

In your example: 在你的例子中:

before_script:
  - npm install
  - nohup node server.js &

stages:
  - test

job_name:
  stage: test
  script:
    - npm run test 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM