Mocha测试失败,并显示"before all"错误.钩 [英] Mocha test fails with error from "before all" hook

查看:1159
本文介绍了Mocha测试失败,并显示"before all"错误.钩的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我了解,如果before方法中发生某些错误,mocha测试框架将抛出​​此错误:

From what I understand, the mocha test framework will throw this error if some error occurs in the before method:

> $(npm bin)/mocha test/*.js


  1) "before all" hook

我尝试了多种尝试来捕获此错误,但是似乎没有任何效果:

I've tried many different things to try and catch this error, but nothing seems to be working:

before(function(done) {
  server = require('../app')
  try {
    server.listen(process.env.PORT)
    done()
    // server.initialize()
    //   .then(() => {
    //     console.info('listening on', process.env.PORT)
    //     server.listen(process.env.PORT, done)
    //   })
    //   .catch(err => {
    //     console.log(err)
    //     done(err)
    //   })
  } catch (err) {
    console.log('outer error', err)
    done(err)
  }
})

从注释掉的代码中,您可以看到服务器具有异步操作,该操作需要在服务器实际开始侦听之前完成.似乎唯一有效的方法是在before块之外初始化服务器,然后在before函数中立即调用done(),或者传递不带参数的函数.但是,这仍然是一个问题,因为在测试开始时服务器尚未初始化.

From the commented out code, you can see that the server has an asynchronous operation I need to complete before the server actually starts listening. The only thing that seems to be working is to initialize the server outside of the before block and either call done() immediately in the before function, or pass a function that doesn't take a parameter. However this is still a problem since the server isn't initialized by the time the test starts.

更有什者,当我连接到调试器时,此代码有效,因此我什至无法检查出什么问题.

Maddeningly, this code works when I connect to a debugger, so I can't even inspect to see what's wrong.

推荐答案

在我发布此问题时,我偶然发现

As I was posting this question, I stumbled on this bug which led me to the discovery that I need to make a call to this.enableTimeouts(false) in the beginning of the before function, like so:

let server
before(function(done) {
  this.enableTimeouts(false)  <----
  server = require('../app')
  server.initialize()
    .then(() => {
      console.info('listening on', process.env.PORT)
      server.listen(process.env.PORT, done)
    })
    .catch(err => {
      console.log(err)
      done(err)
    })
})

希望这可以帮助其他人进行几个小时的调试.

Hopefully this helps someone else a few hours of debugging.

这篇关于Mocha测试失败,并显示"before all"错误.钩的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆