一个单元如何用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.
能够单独测试简单模块很容易并已通过摩卡进行操作然而,我的单元测试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.
正在测试的Route-Function(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");
});
});
});
当我运行此操作时,会出现Error:全局泄漏检测:viewName,data / p>
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屋!