简体   繁体   English

使用Mocha,节点进行单元测试

[英]Unit Testing using mocha, node

I'm new to unit testing in the Node world and am struggling with this: I've setup a after cb to delete the records I've added during my tests, however I keep getting an error Error: done() called multiple times every time I delete the record on the db. 我是Node领域中单元测试的新手,并且为此感到苦恼:我设置了一个after cb来删除在测试期间添加的记录,但是我不断收到错误Error: done() called multiple times每次我删除数据库上的记录。 Here's my code: 这是我的代码:

after((done) => {
    User.deleteOne({email: user_email}, function(err, result) {
        if(err) console.log(err);
        console.log(result);
        done();
    });
});

If I do anything else (like just console something within the after block, I get no error at all. 如果我做其他任何事情(例如只是在after块中进行控制台操作,那么我都不会出错)。

What am I doing wrong? 我究竟做错了什么?

Try with async/await style. 尝试使用async/await样式。

after(async () => {
   const deleteResult = await User.deleteOne({email: user_email});

   console.log(deleteResult);
});

With async/await you don't need to execute done, because mocha automatically handle promises. 使用async/await您不需要执行完成,因为mocha会自动处理promise。
More here and here 这里这里更多

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM