Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do I close pg-promise connection in node.js after all tests have run in jest?

I need to close a PG-Promise database connection after testing a function in Jest.

This is initialised in one place(db.js) and required everywhere it is needed. In the case of the code below, it is required by seed.js which seed.spec.js is testing.

I know there is an afterAll hook in Jest, but that will close the connection everywhere which might cause tests to fail incorrectly?

The problem is solved with the --forceExit option, but it gives an error message and doesn't feel like the right way to solve this?

db.js:

const pgp = require('pg-promise')();
const db = pgp(connection);

module.exports = {db, pgp};

seed.spec.js:

require('dotenv').config();
const {pgp} = require('./db');

expect.extend(require('jest-json-schema').matchers);

const schema = require('./schemas');
const generate = require('./generate');
const seed = require('./seed');
const data = generate();

test ('the data returned by the seed function matches the schema', () => {
  return seed(data)
    .then(outputData => {
      expect(outputData).toMatch(schema);
    });
});

P.S. I have seen similar questions, but none of them quite matches my situation.

like image 936
James Wilson Avatar asked Aug 20 '18 01:08

James Wilson


1 Answers

As with any other database, the connection should be closed in afterAll.

As the reference states, it's either pgp.end() or db.$pool.end():

afterAll(db.$pool.end);

UPDATE

From pg-promise v10.11.0, you no longer need to shut down the pool explicitely. Instead, you can just set connection option allowExitOnIdle: true, to let process exit when pool is idle.

like image 77
Estus Flask Avatar answered Oct 05 '22 13:10

Estus Flask