首页 > 解决方案 > 测试后连接没有关闭?

问题描述

我有一个简单的 postgres.js 包装文件。

const pg =  require("pg")
const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL });

function close() {
  return pool.end()
}

module.exports = {
    end: pool.end,
    close
};

运行一个利用上述 postgres 库的笑话测试用例,如下所示:

const postgres = require("./path/to/postgres.js");

describe("Foo", () => {
  afterAll(() => { 
    return postgres.end();
  })

  it(...)
});

将产生“这通常意味着在您的测试中没有停止异步操作。” 错误消息并挂在那里。

但是,如果我将行更改postgres.end()postgres.close(),它会正确关闭数据库连接并在测试完成后终止 jest。

我的问题是它在功能上不做同样closeend事情吗?为什么一个关闭连接而另一个没有?

标签: javascriptnode.jsjestjsnode-postgres

解决方案


你的end函数只是执行pool.end而不是作为一个承诺返回它,所以它不相似。为了更好的可视化,您当前的代码基本上是这样做的:

    function close() {
        return pool.end()
    }

    function end() {
      pool.end()
    }

module.exports = {
    end,
    close
};

推荐阅读