javascript - 在 Jest 运行所有测试后,如何关闭 node.js 中的 pg-promise 连接?

标签 javascript node.js postgresql jestjs pg-promise

我需要在 Jest 中测试功能后关闭 PG-Promise 数据库连接。

这是在一个地方初始化的 (db.js) 和 required 在任何需要的地方。对于下面的代码,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/

相关文章:

javascript - 有什么方法可以查看 gulp watch 处理了哪些文件?

javascript - 将 JSON 附加到 HTML

javascript - 使用 typeahead 和 bloodhound 显示点击建议的完整列表

javascript - 如何将 env 映射添加到 gltf 对象上

node.js - 通过 nodejs 和 websockets 将功能从 openlayers 保存到 postgis

database - Postgres : Do I need to create temporary tables in each session?

java - Hibernate-search 5.0 空间 - 不确定它是否在哈希中存储纬度/经度

javascript - 将包含对象的数组传递到数据表中

node.js - 查找未设置 DynamoDB 属性*或*大于 x 的项目

node.js - 如何在同构Web应用程序中正确配置React-Toolbox而不会出现 "asset not found"错误