我在使用 Express 在许多方面进行单元测试时遇到了麻烦,似乎缺乏有关它的文档和一般在线信息。
到目前为止,我发现我可以使用名为 supertest ( https://github.com/visionmedia/superagent ) 的库来测试我的路由,但是如果我将路由和 Controller 分开怎么办,我怎样才能独立于它们的路由来测试我的 Controller 。
这是我的测试:
describe("Products Controller", function() {
it("should add a new product to the mongo database", function(next) {
var ProductController = require('../../controllers/products');
var Product = require('../../models/product.js');
var req = {
params: {
name: 'Coolest Product Ever',
description: 'A very nice product'
}
};
ProductController.create(req, res);
});
});
req 很容易制作模型。 res 没有那么多,我尝试抓取express.response,希望我可以注入(inject)它,但这没有奏效。有没有办法模拟 res.send 对象?或者我在这方面走错了路?
最佳答案
当您测试路线时,您实际上并没有使用内置函数。例如,ProductController.create(req, res);
您基本上需要做的是,在端口上运行服务器并为每个 url 发送请求。正如您提到的 supergent,您可以遵循此代码。
describe("Products Controller", function() {
it("should add a new product to the mongo database", function(next) {
const request = require('superagent');
request.post('http://localhost/yourURL/products')
.query({ name: 'Coolest Product Ever', description: 'A very nice product' })
.set('Accept', 'application/json')
.end(function(err, res){
if (err || !res.ok) {
alert('Oh no! error');
} else {
alert('yay got ' + JSON.stringify(res.body));
}
});
});
});
您可以引用superagent请求示例here .
关于node.js - 单元测试 Express Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21499408/