4

I'm trying to do some TDD with my following stack

  • Jest
  • Node
  • Koa2
  • SuperTest
  • Knex
  • Objection

My problem starts with the open handler of the koa server and I could solve that with the instance of the server and close it with server.close()

However, I have the same problem with knex; It leaves the server open and I have to run the knex.close to stop it. With that i can avoid the following error message

Jest did not exit one second after the test run has completed.

This usually means that there are asynchronous operations that weren't >stopped in your tests. Consider running Jest with --detectOpenHandles to >troubleshoot this issue.

knex.config

const config = {
  development: {
    client: 'pg',
    connection: process.env.DATABASE_URL,
    migrations:{
      directory:"./migrations/"
    },
    pool: { min: 0, max: 7 }
  },
  test: {
    client: 'pg',
    connection: process.env.DATABASE_URL,
    migrations:{
      directory:"./migrations/"
    },
    pool: { min: 0, max: 7 }
  },
//TBD
  staging: {
    client: 'postgresql',
    connection: {
      database: 'my_db',
      user:     'username',
      password: 'password'
    },
    pool: {
      min: 2,
      max: 10
    },
    migrations: {
      tableName: 'knex_migrations'
    }
  },
  //TBD
  production: {
    client: 'postgresql',
    connection: {
      database: 'my_db',
      user:     'username',
      password: 'password'
    },
    pool: {
      min: 2,
      max: 10
    },
    migrations: {
      tableName: 'knex_migrations'
    }
  }

}


module.exports = config;

user.model.js

'use strict';

const knex = require('../config/db/knex');
const { Model } = require('objection');
Model.knex(knex);

class User extends Model {

  // Table name is the only required property.
  static get tableName() {
    return 'user';
  }

  // Custom function to close knex
  static close() {
    knex.destroy();
  }
}

module.exports = User;

user.test.js

const supertest = require('supertest');
const server = require('../../server');
var request = require("supertest").agent(server);


describe("Test users routes", () => {
  let Model;
  beforeAll(async () => {
    // do something before anything else runs
    console.log('Jest starting!');
    Model = require('../../models/user.model')
  });
// close the server after each test
afterAll(() => {
  server.close();
  Model.close();
  console.log('server closed!');
});


  test("Get /",async () => {
       let res = await request.get('/users/');

       expect(res.status).toBe(200);

  });
});

I'm pretty sure it could be a better approach solution for what I did, maybe something related with the pool or some callback on the knex.cofing but I'm not sure.

Thank you

Archagy
  • 135
  • 1
  • 12

0 Answers0