Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/34.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 用Mocha测试抛出异步函数_Node.js_Asynchronous_Mongoose_Mocha.js - Fatal编程技术网

Node.js 用Mocha测试抛出异步函数

Node.js 用Mocha测试抛出异步函数,node.js,asynchronous,mongoose,mocha.js,Node.js,Asynchronous,Mongoose,Mocha.js,我尝试使用mocha框架测试MongoDB Mangose模型的有效性 describe 'User', -> describe 'create', -> it 'should reject a user with an already existing mail', (done) -> User.create mail: "minimal@gmail.com" , (err) -> if err t

我尝试使用mocha框架测试MongoDB Mangose模型的有效性

describe 'User', ->
  describe 'create', ->
    it 'should reject a user with an already existing mail', (done) ->
      User.create
        mail: "minimal@gmail.com"
      , (err) ->
          if err then done() else done(false)
我预计Mongoose会出现验证错误,因为此邮件已被接收,但该字段被标记为唯一

如何测试特定错误?我认为最干净的方法是使用
should.throws(回调,message regexp)
,但是,这不起作用,因为Model#create是异步的

推荐信(对我没有帮助)

问题在于
done()
回调。第一个参数检查错误,如果出现错误,它必须为true-y。在代码中,您总是传递false-y值,这意味着测试运行成功

在您的情况下,您希望使用:

if err then done() else done(true)
您可以添加字符串或其他任何内容,而不是true

编辑 异步函数通常不会抛出错误。实际使用异常时会抛出错误(
抛出新错误(…)
)。相反,Mongoose只调用回调函数,将非false值传递给
err
参数(第一个参数)。因此,只需检查
err.toString()
err.message
是否匹配您的搜索字符串

例如,在回调中(假设您使用的是Should.js,正如您的评论让我想到的那样;否则,将其转换为您实现的任何其他框架)


(仅此而已!)

使用此解决方案,我的测试将验证任何类型的错误。我想知道如何准确地要求mongoose生成ValidationError。这类似于
should.throws(block、[error]、[message])
。但是,对于异步测试来说,这并不是开箱即用的。好吧,所以您不应该测试“should.throws”,因为Mongoose不会抛出错误。相反,如果
err.toString()
err.message
与您想要的值匹配,只需在回调中进行测试。我已经更新了答案。
should(err).be.not.empty
err.toString().should.match(/ValidationError/)