I need to close a PG-Promise database connection after testing a function in Jest.
This is initialised in one place(db.js) and require
d 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.
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With