首页 > 解决方案 > 在所有测试都以开玩笑的方式运行后,如何在 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我见过类似的问题,但没有一个完全符合我的情况。

标签: javascriptnode.jspostgresqljestjspg-promise

解决方案


与任何其他数据库一样,连接应在afterAll.

正如参考文献所述,它是pgp.end()or db.$pool.end()

afterAll(db.$pool.end);

更新

从 pg-promise 开始v10.11.0,您不再需要显式关闭池。相反,您可以设置连接选项allowExitOnIdle: true,让进程在池空闲时退出。


推荐阅读