【问题标题】:mocha hangs after tests have finished测试完成后 mocha 挂起
【发布时间】:2018-12-05 09:33:19
【问题描述】:

我在nodejs中运行mocha,测试一个异步函数,我没有忘记调用done,但是测试通过后mocha就一直挂在那里,什么都不等。甚至我为after() 放置的函数也完成了,但是mocha 直到我CTRL+C 才退出。

代码如下:

describe("tests the user_handler", () => {
  beforeEach(resetDB);
  after(resetDB);

  it("returns null when searching for a user with an id that does not exists", (done) => {
    userHandler.findUserById( {user_id: "U-1234567"} )
      .then((result) => {
        expect(result).to.be.null;
        done()
      })
  })
})

这是输出:

tomk@tomk-Latitude-7480 ~/workspace/fundme/server (login_with_github) $ npm test

> fundme-server@1.0.0 test /home/tomk/workspace/fundme/server
> mocha tests/*.spec.js



  tests the user_handler
resetDB called
resetDB finished
    ✓ returns null when searching for a user with an id that does not exists
resetDB called
resetDB finished


  1 passing (64ms)

^CTerminated

如果它是相关的(虽然我不这么认为),被测试的函数是使用来自mysql2 库的mysqlConnectionPool 的承诺版本

这是我用于beforeEachafterresetDB 函数的代码:

function resetDB() {
  console.log("resetDB called")
  command =
    "mysql" +
    " --defaults-extra-file=" + mysql_conf_file +
    " --host " + process.env['MYSQL_HOSTNAME'] +
    " -D fundme < " + testing_db_file_location;
  cp.execSync(command);
  console.log("resetDB finished")
}

对我可能忘记的东西有什么想法吗?

【问题讨论】:

  • resetDB 看起来像什么或做什么?
  • 它执行一个命令,将 mysql 数据库重置为其初始状态。我将编辑我的问题并添加代码
  • 你能在释放连接池之后添加一些东西吗?或者你确定它实际上是发布? pool.releaseConnection(conn);docs 来看,这似乎很关键。我能想到的唯一另一件事是您生成的进程可能不会退出。你能检查一下你使用的任何进程监视器是否是这种情况吗?
  • 你完全正确!就是这样!我在想,如果我使用mysqlConnectionPool.query() 而不手动获取连接并对其执行查询,它将为我处理连接并关闭它。如果是我,那就太傻了。我在 mysqlConnectionPool.end() 之后添加了另一个函数 - 修复了它。谢谢
  • 好的,我将把它作为答案发布。

标签: node.js mocha.js


【解决方案1】:

既然你提到你正在使用mysqlConnectionPool。我猜您可能没有关闭导致您的程序继续等待所有连接关闭的池。

根据文档判断:Using connection pools

// Don't forget to release the connection when finished!

完成后释放连接至关重要。检查并确保您在每个或所有测试中都这样做after()

// For pool initialization, see above
pool.getConnection(function(err, conn) {
   // Do something with the connection
   conn.query(/* ... */);
   // Don't forget to release the connection when finished!
   pool.releaseConnection(conn);
})

或者,由于这只是一个测试文件,关闭 after 中的所有连接将确保 mocha 在最后停止:

after(() => { mysqlConnectionPool.end() })

【讨论】:

  • 如果我不使用mysqlConnectionPool怎么办?
  • @AndrewKoster 如果您使用的是createConnection,我认为有一个end 方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-11
相关资源
最近更新 更多