繁体   English   中英

在所有测试都在玩笑中运行后,如何关闭 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选项解决,但它给出了一条错误消息,并且感觉不是解决此问题的正确方法?

数据库.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()db.$pool.end()

afterAll(db.$pool.end);

更新

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

我找到的最接近的解决方案是使用setupFilesAfterEnv Jest 配置选项

// 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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM