一个单元如何使用 Express 测试路由? [英] How does one unit test routes with Express?
问题描述
我正在学习 Node.js,并且一直在玩 Express.真的很喜欢这个框架;但是,我无法弄清楚如何为路由编写单元/集成测试.
I'm in the process of learning Node.js and have been playing around with Express. Really like the framework;however, I'm having trouble figuring out how to write a unit/integration test for a route.
能够对简单模块进行单元测试很容易,并且已经使用 Mocha 做到了;但是,我使用 Express 的单元测试失败了,因为我传入的响应对象没有保留值.
Being able to unit test simple modules is easy and have been doing it with Mocha; however, my unit tests with Express fail since the response object I'm passing in doesn't retain the values.
被测路由功能(routes/index.js):
exports.index = function(req, res){
res.render('index', { title: 'Express' })
};
单元测试模块:
var should = require("should")
, routes = require("../routes");
var request = {};
var response = {
viewName: ""
, data : {}
, render: function(view, viewData) {
viewName = view;
data = viewData;
}
};
describe("Routing", function(){
describe("Default Route", function(){
it("should provide the a title and the index view name", function(){
routes.index(request, response);
response.viewName.should.equal("index");
});
});
});
当我运行它时,它因错误:检测到全局泄漏:viewName,数据"而失败.
When I run this, it fails for "Error: global leaks detected: viewName, data".
我哪里出错了才能让它正常工作?
Where am I going wrong so that I can get this working?
有没有更好的方法可以在这个级别对我的代码进行单元测试?
Is there a better way for me to unit test my code at this level?
更新1. 更正了代码片段,因为我最初忘记了it()".
Update 1. Corrected code snippet since I initially forgot "it()".
推荐答案
更改您的响应对象:
var response = {
viewName: ""
, data : {}
, render: function(view, viewData) {
this.viewName = view;
this.data = viewData;
}
};
它会起作用.
这篇关于一个单元如何使用 Express 测试路由?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!