带有异步回调的单元测试快速路由 [英] unit testing express route with async callback

查看:86
本文介绍了带有异步回调的单元测试快速路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用express在node.js中编写应用程序.
我将路线定义与express分开了,因此我可以对它进行单元测试而不会嘲笑express.
我所做的是:

I'm writing an app in node.js using express.
I seperated the route definition from express so I will be able to unit test it without mocking out express.
What I did is:

文件:usersRoutes.js

 var routes = {
  getAll: function(req,res) {
    var db = req.db; // req.db is initialized through a dedicated middleware function
    var usersCollection = db.get('users');
    usersCollection.find({},{limit:10},function(e,results){
      res.send(results);
    });
  }
};

module.exports = routes;

文件:users.js

var express = require('express');
var router = express.Router();
var routes = require('./usersRoutes');

/* GET users listing. */
router.get('/', routes.getAll);

module.exports = router;

,最后进入 app.js :

var users = require('./routes/users/users.js');
app.use('/users', users);

现在,我想编写一个单元测试,以检查是否使用正确的参数调用了req.send. 我无法找出正确的方法,因为req.send是异步调用的.
对该功能进行单元测试的正确方法是什么?

Now, I want to write a unit test that checks that req.send is being called with the right parameter. I'm having trouble figuring out the correct way because the req.send is invoked asynchronously.
What is the correct way to unit test this function?

推荐答案

如果您使用的是Mocha,它将提供完成"功能,您可以将其注入回调中,它将告诉Mocha测试是异步的,应等待该操作完成.函数被称为

if you are using mocha it provides the "done" function that you can inject into your callback and it will tell mocha that test is async and should wait until that function is called

it('should do something',function(done){
  reuest.send(function(){
     expect(true).toEqual(true);
     done()
  })
})

或类似的我不记得的东西,这是100%正确的语法,但是非常接近 这对回调很有用,但另一方面,如果您使用诺言,则应检查chai和mocha的诺言断言,这很酷

or something like that i don't remember is this is 100% the right syntax, but is pretty close this is good for callbacks but if you are using promises on the other hand you should check chai and mocha's promises assertions, are pretty cool

这篇关于带有异步回调的单元测试快速路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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