在所有测试开玩笑 运行 之后,如何关闭 node.js 中的 pg-promise 连接?
how do I close pg-promise connection in node.js after all tests have run in jest?
我需要在 Jest 中测试功能后关闭 PG-Promise 数据库连接。
这是在一个地方初始化的(db.js),require
d 在任何需要的地方。对于下面的代码,seed.js 需要 seed.spec.js 正在测试。
我知道 Jest 中有一个 afterAll
钩子,但这会关闭所有地方的连接,这可能会导致测试错误地失败?
问题 是 使用 --forceExit
选项解决的,但它给出了一条错误消息,感觉不是解决此问题的正确方法?
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。我看过类似的问题,但是none个很符合我的情况。
与任何其他数据库一样,连接应在 afterAll
后关闭。
如 the reference 所述,它是 pgp.end()
或 db.$pool.end()
:
afterAll(db.$pool.end);
更新
从 pg-promise v10.11.0
开始,您不再需要显式关闭池。相反,您可以只设置连接选项 allowExitOnIdle: true
,让进程在池空闲时退出。
我找到的最接近的解决方案是使用 setupFilesAfterEnv
Jest configuration option.
// jest.config.js
module.exports = {
setupFilesAfterEnv: ['./jest/setup/afterAll']
}
// afterAll.js (path: ./jest/setup/afterAll.js)
const { db } = require('../../src/db')
afterAll(db.$pool.end)
我需要在 Jest 中测试功能后关闭 PG-Promise 数据库连接。
这是在一个地方初始化的(db.js),require
d 在任何需要的地方。对于下面的代码,seed.js 需要 seed.spec.js 正在测试。
我知道 Jest 中有一个 afterAll
钩子,但这会关闭所有地方的连接,这可能会导致测试错误地失败?
问题 是 使用 --forceExit
选项解决的,但它给出了一条错误消息,感觉不是解决此问题的正确方法?
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。我看过类似的问题,但是none个很符合我的情况。
与任何其他数据库一样,连接应在 afterAll
后关闭。
如 the reference 所述,它是 pgp.end()
或 db.$pool.end()
:
afterAll(db.$pool.end);
更新
从 pg-promise v10.11.0
开始,您不再需要显式关闭池。相反,您可以只设置连接选项 allowExitOnIdle: true
,让进程在池空闲时退出。
我找到的最接近的解决方案是使用 setupFilesAfterEnv
Jest configuration option.
// jest.config.js
module.exports = {
setupFilesAfterEnv: ['./jest/setup/afterAll']
}
// afterAll.js (path: ./jest/setup/afterAll.js)
const { db } = require('../../src/db')
afterAll(db.$pool.end)