Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run mocha tests and node in a single npm test command ? (CI)

I want to use Circle CI to integrate a git project.

I'm using mocha for my tests .

What i want to do?

When running npm test I want:

  • my node server to start
  • my test file to run

How can I run a single npm test command to run both node and my mocha tests which are already wrapped in a single index.js file.

I have tried this in my package.json:

  "scripts": {
    "test": "node server/app.js & mocha server/tests/index.js",
    "start": "node server/app.js",
    "postinstall": "bower install"
   }

The problems with the above

  • My server takes some time to start and the tests fail since they run before the server starts

Is there a standard way to run a server and the tests with a single command but I'm missing something?

like image 704
Alex Lemesios Avatar asked Oct 29 '22 20:10

Alex Lemesios


2 Answers

If it is possible at all in your case I'd suggest using something like supertest to do the testing. This way, you can avoid having to start a server before starting the test.

I understand that there are scenarios where using supertest is not possible. In such case, you could poll your server in a before hook before all tests to wait until it is ready:

before(function (done) {
  // Set a reasonable timeout for this hook.
  this.timeout(5000);

  function check() {
    if (serverIsReady()) {
      done();
      return; 
    }

    // The server is no ready, check again in 1/10th of a second.
    setTimeout(check, 100);
  }

  check(); // Start checking.
});

I'm not sure what serverIsReady should be precisely in your case. It could be an attempt at getting a trivial path from your server like issuing a GET on the path /.

like image 68
Louis Avatar answered Nov 11 '22 03:11

Louis


I think the key is to run your node server in your test, rather than trying to initialise it in another process.

Your mocha test should start with a require to your app, then each of your tests can interact with it.

For example:

var http = require('http');

var server = http.createServer(function(req, res){
  res.end('Hello World\n');
})

server.listen(8888);

describe('http', function(){
  it('should provide an example', function(done){
    http.get({ path: '/', port: 8888 }, function(res){
      expect(res).to.have.property('statusCode', 200);
      done();
    })
  })
})
like image 43
filype Avatar answered Nov 11 '22 04:11

filype