user12057543
user12057543

Reputation:

Mocha/ Supertest is not exiting on completion of tests

I am using the mocha testing framework, and after running the following test it does not exit. I have tried Promises and async await with no luck. --exit at the end of the mocha command works, but I want to find the source of the issue.

I am wondering if it is the knex database connection when running beforeEach and afterEach functions. However, I do not know how to disconnect the db connection other than destroy(), and if this is used the following tests do not run.

Can anybody see anything within the code that could be causing this issue? Or recommend another way to remedy this?


const app = require('../../app');
const request = require('supertest');


describe('Route: /' + route, () => {
    let token = '';
    let route = 'user';

    before(function (done) {
        const user = {email: '[email protected]', password: 'password'};
        request(app)
            .post('/login')
            .send(user)
            .end((err, res) => {
                token = res.body.token;
                done();
            });
    });

    beforeEach(async () => {
        await knex.migrate.rollback();
        await knex.migrate.latest();
        await knex.seed.run();
    });
    afterEach(() => knex.migrate.rollback());

    it(`should not be able to consume /${route} since no token was sent`, (done) => {
        request(app)
            .get(`/${route}`)
            .expect(401, done)
    });

    it(`should be able to consume /${route} since a valid token was sent`, (done) => {
        request(app)
            .get(`/${route}`)
            .set('Authorization', 'Bearer ' + token)
            .expect(200, done);
    });
});

Upvotes: 3

Views: 2329

Answers (1)

user12057543
user12057543

Reputation:

For anyone who comes across this and has a similar problem.

Using the following links;
- GitHub mocha debug example
- Mocha docs -exit
- wtfnode

I was able to debug the problem.
wtfnode used within my test showed me that my database was still connected with the console reading.

const wtf = require('wtfnode');

after(wtf.dump());  // place within test describe body

Returned;

- Sockets:
  - 127.0.0.1:58898 -> 127.0.0.1:5432
    - Listeners:
      - connect: Connection.connect @ <user_path>/node_modules/pg/lib/connection.js:59

I am using knex to connect to the database, so I've added code below to the file helper.js in my test directory.

/test/helper.js

const knex = require('../database/db');


before(function () {
    if (!knex.client.pool) return knex.initialize();
});

beforeEach(async function () {
    await knex.migrate.rollback();
    await knex.migrate.latest();
    await knex.seed.run();
});

afterEach(function () {
    return knex.migrate.rollback()
});

after(function () {
    return knex.destroy();
});

Upvotes: 3

Related Questions