【问题标题】:Connection not closed after test?测试后连接没有关闭?
【发布时间】:2019-11-22 17:30:28
【问题描述】:

我有一个简单的 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 在功能上不做同样的事情吗?为什么一个关闭连接而另一个没有?

【问题讨论】:

  • end: pool.end.bind(pool)?考虑到差异,我猜是this 绑定问题。

标签: javascript node.js jestjs node-postgres


【解决方案1】:

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

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

    function end() {
      pool.end()
    }

module.exports = {
    end,
    close
};

【讨论】:

  • 为什么你认为承诺没有返回?
猜你喜欢
  • 2015-10-21
  • 1970-01-01
  • 2013-03-21
  • 2018-12-28
  • 1970-01-01
  • 2018-03-01
  • 2019-06-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多