我需要在 Jest 中测试功能后关闭 PG-Promise 数据库连接。
这是在一个地方初始化的 (db.js) 和 require
d 在任何需要的地方。对于下面的代码,seed.js 需要它,seed.spec.js 正在测试它。
我知道 Jest 中有一个 afterAll
钩子(Hook),但这会关闭所有地方的连接,这可能会导致测试错误地失败?
问题是用--forceExit
选项解决了,但是它给出了一个错误信息并且感觉不是解决这个问题的正确方法?
db.js:
const pgp = require('pg-promise')();
const db = pgp(connection);
module.exports = {db, pgp};
种子.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);
});
});
附言我见过类似的问题,但没有一个与我的情况很相符。
最佳答案
与任何其他数据库一样,连接应在 afterAll
中关闭。
作为the reference状态,它是 pgp.end()
或 db.$pool.end()
:
afterAll(db.$pool.end);
更新
从 pg-promise v10.11.0
开始,您不再需要显式关闭池。相反,您可以只设置连接选项 allowExitOnIdle: true
,让进程在池空闲时退出。
关于javascript - 在 Jest 运行所有测试后,如何关闭 node.js 中的 pg-promise 连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51923186/