fanfan fanfan - 2 months ago 44
Node.js Question

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. My app is written in node.js, and the file looks like this:

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. 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?

Answer Source

I have the exact same setup, with 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. I use Mocha + Chai (with chai-http). You can also use supertest to do the same.

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);
    });
  });
});