我需要在 Jest 测试函数后关闭 PG-Promise 数据库连接。
它在一个地方(db.js)初始化,并且在需要的每个地方都被 require
。在下面的代码中,它被 seed.js 所需,而 seed.spec.js 正在测试它。
我知道 Jest 中有一个 afterAll
钩子,但那会关闭所有连接,可能会导致测试不正确地失败?
这个问题可以通过使用 --forceExit
选项来解决,但它会给出错误消息,感觉不是正确的解决方法?
db.js:
const pgp = require('pg-promise')();
const db = pgp(connection);
module.exports = {db, pgp};
seed.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);
});
});
附注:我已经看到了类似的问题,但没有一个完全符合我的情况。
afterAllTestSuites()
钩子。 - James WilsonafterAll
就是它字面意思的含义。 - Estus Flask