1

I have an Express http server in nodeJS and I am using chai mocha for unittest or integration tests. These tests run fine, but after the test the server should stop. But the server never stops. I have tried lot of possibitys which are commented out in the code below. I see that all functions are called but the agent.close(). is not executed or it is ignored by the server.

I have looked on these sites:

And on this site is stated that the method I am using is the right one but it is not working:

Here is my code.

import * as chai from 'chai';
import { expect } from 'chai'
import chaiHttp = require('chai-http');

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

//let testServer;

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

describe('Relaties', () => {
    let agent = chai.request.agent(app);

    beforeEach(function (done) {
        console.log('outer describe - beforeEach');

        //testServer = require('../../server')

        agent
            .put('/api/ehrm-klantnr/medewerker/login')
            .send({ email: 'admin@sfgtest.com', wachtwoord: '<secret>' })
            .then(function (res) {
                expect(res).to.have.cookie('SESSIONID');
                done();
            });
    });

    afterEach(function (done) {
        console.log('Describe - After');
        agent.close();

        //delete require.cache[require.resolve( '../../server' )]

        done();

        //server.close();
        //agent.close();
        //testServer.close();

    });


    describe('Ophalen alle relaties met: GET /api/ehrm-klantnr/relatie', () => {
        it('should get alle relaties', (done) => {

            agent.get('/api/ehrm-klantnr/relatie')
                .set('meta', '1')
                .then(function (res) {
                    expect(res).to.have.status(200);
                    done();
                });
        });
    });

Anybody an idea what I am doing wrong ?

Ben
  • 594
  • 1
  • 9
  • 24
  • Ok no answers, it means I guess I am using the wrong tools? Lets forget about the chai-http implementation because this is never going to work. – Ben Jun 03 '19 at 14:13

1 Answers1

1

I finally found the answer and it is a simple solution. This can be solved by just adding a simple parameter to the mocha command in the npm start script line in the package.json file:

The npm start test config must be like this, and the --exit --r parameter are important:

"scripts": {
    "ng": "ng",
    "test": "mocha --exit -r ts-node/register **/*.spec.ts",  //this is the correct config
    "start-server": "./node_modules/.bin/ts-node ./server.ts",
    "server": "./node_modules/.bin/nodemon -w . --ext \".ts\" --exec \"npm run start-server\""
  },
Ben
  • 594
  • 1
  • 9
  • 24