4

I'm trying to get a TDD workflow going with koa2/mocha/chai/chai-http but my problem is that when I run the tests the koa2 server keeps running after the tests are finished. So that I have to Ctrl+C (kill) it every time.

Can anyone tell me how to setup a TDD workflow where the server gets stopped after all tests are run?

Also, I'd like to watch the test files for changes and re-run the tests as soon as changes are detected... can anyone help with that? can't find anything on the net -.-

What I currently have (simplified):

package.json:

"scripts": {
   "watch-server": "nodemon --watch 'src/**/*' -e ts,tsx --exec 'ts-node' ./src/server.ts",
   "test": "./node_modules/mocha/bin/mocha --compilers ts:ts-node/register test/**/*.ts"
},

server.ts:

app.use(routes_v1.routes());

export const server = app.listen(3000, () => {
    console.log('Server running on port 3000');
});

test:

process.env.NODE_ENV = 'test';

import * as chai from 'chai';
const chaiHttp = require('chai-http');

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

import { server } from '../../../src/server';

describe('routes : login / register', () => {
  describe('POST /sign_in', () => {
    it('should return unauthorized for invalid user', (done) => {
      chai.request(server)
      .post('/sign_in')
      .send({email: "test@test.de", password: "somePassword"})
      .end((err, res) => {
        res.status.should.eql(401);
        should.exist(err);
        done();
      });
    });

    it('should return authorized for valid user', (done) => {
      chai.request(server)
      .post('/sign_in')
      .send({email: 'authorized@test.de', password: "authorizedPassword"})
      .end((err, res) => {
        res.status.should.eql(200);
        should.exist(res.body.token);
        done();
      });
    });
  });

Thank you.

Oles Savluk
  • 3,877
  • 1
  • 21
  • 38
  • can you share an example of the skeleton `src/server` as well? Trying to get this to work with my koa2 app but I think I'm hitting a race condition. – Dylan Pierce Apr 09 '20 at 21:55

1 Answers1

2

Starting from version 4.0 Mocha will no longer force the process to exit once all tests complete. You can use CLI parameter -exit to exit from the process when tests are finished:

"test": "mocha ... -exit"

Or another option, which gives you more control over the process, is to use Hooks. So you can start the server before running test(s) and stop it after:

describe('...', () => {
  let server;

  before(() => {
    server = app.listen()
  });
  after(() => {
    server.close()
  });

  ...
})

As an example, you can take a look at this test. It is using Jest and supertest, but idea is the same.

Oles Savluk
  • 3,877
  • 1
  • 21
  • 38