如何在nodejs中模拟请求和响应来测试中间件/控制器? [英] How to mock request and response in nodejs to test middleware/controllers?

查看:166
本文介绍了如何在nodejs中模拟请求和响应来测试中间件/控制器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序有几层:中间件,控制器,管理器。控制器接口与中间件一样:(req,res,next)。



所以我的问题是:如何在没有启动服务器并向localhost发送真实请求的情况下测试我的控制器。我想做的是创建请求,响应实例作为nodejs,然后调用controller方法。



这样的一个例子:

  var req = new Request()
var res = new Response()
var next = function(err){console.log(' lala')}
controller.get_user(req,res,next)

任何建议高度赞赏谢谢!



我想这样做的原因是最后我想测试响应对象是否包含玉视图的正确变量。

解决方案

由于JavaScript是一种动态类型的语言,您可以创建模拟对象并将其传递给控制器​​,如下所示:

  var req = {}; 
var res = {};
var next = function(err){console.log('lala')}
controller.get_user(req,res,next)

如果您的控制器需要您的请求或响应对象中的特定数据或功能,则需要在您的模拟器中提供此类数据或功能。例如,

  var req = {}; 
req.url =http://google.com; // fake the Url

var res = {};
res.write = function(chunk,encoding){
//假写方法
};

var next = function(err){console.log('lala')}
controller.get_user(req,res,next)


My application has several layers: middleware, controllers, managers. Controllers interface is identical to middlewares one: (req, res, next).

So my question is: how can I test my controllers without starting the server and sending 'real' requests to localhost. What I want to do is to create request, response instances as nodejs does and then just call controllers method.

Something like this:

var req = new Request()
var res = new Response()
var next = function(err) {console.log('lala')}
controller.get_user(req, res, next)

Any advice is highly appreciated. Thanks!

P.S. the reason why I want to do this is that at the end I would like to test whether the response object contains correct variables for the jade views.

解决方案

Since JavaScript is a dynamically typed language you can create mock objects and passing them to your controllers as follow:

var req = {};
var res = {};
var next = function(err) {console.log('lala')}
controller.get_user(req, res, next)

If your controller needs a particular piece of data or functionality from your request or response object you'll need to provide such data or functionality in your mocks. For example,

var req = {};
req.url = "http://google.com"; // fake the Url

var res = {};
res.write = function(chunk, encoding) { 
  // fake the write method 
};

var next = function(err) {console.log('lala')}
controller.get_user(req, res, next)

这篇关于如何在nodejs中模拟请求和响应来测试中间件/控制器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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