assert.throws异步方法 [英] assert.throws on asynchronous method

查看:176
本文介绍了assert.throws异步方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Mocha单元测试中尝试使用assert.throws时遇到了麻烦,

I am having troubles trying to use assert.throws in my Mocha unit tests,

我有这种方法:

var getMetadatas = function (file, callback) {
  fs.readFile(file, {encoding: 'utf-8'}, function(err, data){
    // stuff
      if (somethingWentWrong) 
        throw new Error('Something went wrong')
    // callback call
  })
}

在单元测试中,我有:

it('should throw an error when passing a bad formatted file', function(){ 
  assert.throws(
    getMetadatas('someBadFormattedFile', function(metadatas){})
  )
})

我得到的结果是随机的,有时会引发错误(我得到了Uncaught Error: something went wrong),并且测试失败了,有时它会通过.

The results I get are random, sometimes the error is being thrown (I got Uncaught Error: something went wrong) and the test is failing, sometimes it passes.

我还尝试了其他一些方法,例如通过回调传递错误并执行以下操作:

I have tried a couple of other things, such as passing the error through the callback and do:

var fn = function(){ 
  parse.getMetadatas('test/test_incorrect.md', function (err, metas) {
      if (err) throw err
  })
}
assert.throws( function() { fn() }, Error )

我得到的输出是:AssertionError: Missing expected exception (Error)..,所以我想他什么也没看到...

And I got as output: AssertionError: Missing expected exception (Error).. so I guess he doesn't see anything...

我可以使assert.throws正常工作的唯一方法是使用同步功能:

The only way I can get assert.throws to work as I expected is with a synchronous function:

assert.throws(
  function () {throw new Error('error')}
)

我想知道它是否必须对done()做一些事情,但是即使在回调中调用它也没有成功.我错过了什么吗?

I was wondering if it had to do something with done(), but still even by calling it in my callback, no success. Did I miss something?

推荐答案

我设法通过改进David Norman的答案使它起作用.正如我在问题中指出的那样,我的测试缺少done()调用,但是即使我在throw err之后调用它,我在Mocha上也有超时异常.无论如何,这是我用于测试我编写的另一种异步方法的代码段,并且该代码段通过并且没有超时错误:

I managed to get it to work by improving David Norman's answer. As I stated in my question, my test lacked the done() call, but even if I was calling it after the throw err, I was having a timeout exception with Mocha. Anyway, this is the code snippet I used for the test of another asynchronous method I wrote, and it pass and does not get a timeout error:

var fn = function () {
  fs.rmrf(path.join(pathDir, 'non', 'existing'), function (err) {
    done()
    assert.ifError(err)
  })
}
assert.throws(function () { fn() } , /No directory/)

/No directory/fn的回调中引发的错误的文本描述匹配的地方.可能是Error,但我想确定检测到的错误是assert.throws.

Where /No directory/ matches the text description of the Error being thrown in fn's callback. It could be Error but I wanted to be sure of wich error assert.throws was detecting.

这篇关于assert.throws异步方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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