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.
afterAllTestSuites()
hook – ThoerafterAll
does what it says. – Procuratorpg-promise
instances. They don't know of each other, unless they maintain common pool in a database - and I'm quite sure they don't. DidafterAll
fail for you? Because I'd expect it to be proper solution here. On the other hand,globalTeardown
may not work because it's unaware of otherpg-promise
module instances. – Procurator