javascript - 在所有测试都以开玩笑的方式运行后,如何在 node.js 中关闭 pg-promise 连接?
问题描述
在 Jest 中测试一个函数后,我需要关闭一个 PG-Promise 数据库连接。
这在一个地方(db.js)初始化,并在需要的地方初始化require
。在以下代码的情况下,seed.js 需要种子.spec.js正在测试哪个。
我知道 Jest 中有一个afterAll
钩子,但这会关闭所有地方的连接,这可能会导致测试错误地失败?
该选项解决了问题,但它--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);
});
});
PS我见过类似的问题,但没有一个完全符合我的情况。
解决方案
与任何其他数据库一样,连接应在afterAll
.
正如参考文献所述,它是pgp.end()
or db.$pool.end()
:
afterAll(db.$pool.end);
更新
从 pg-promise 开始v10.11.0
,您不再需要显式关闭池。相反,您可以设置连接选项allowExitOnIdle: true
,让进程在池空闲时退出。
推荐阅读
- python - 使用 DJango 和 SQlite3 更改单元格的默认值
- java - 如何使 DialogFragment 在活动主体中更改文本?
- javascript - PayPal 货币换算不正确
- python-chess - 找出该举动是否在蟒蛇国际象棋中获得一块棋子的最佳方法是什么?
- php - 获得未定义的变量错误,但我确定它已定义
- python - 预处理和加载 NSL_KDD 数据集
- javascript - firebase 错误 reference.push 失败:第一个参数在属性“电子邮件”中包含未定义
- python-3.x - 如何在beautifulsoup中刮取相同的元素标签
- r - R - dplyr/purrr - 从现有列对的函数创建新列
- javascript - i18n.changeLanguage 将部分字符串发送到 locize,不是 nn-NO,而是只有 nn