【问题标题】:Unit Testing Express Controllers单元测试 Express 控制器
【发布时间】:2014-02-01 14:43:02
【问题描述】:

我在多个方面都无法使用 Express 进行单元测试,似乎缺乏关于它的在线文档和一般信息。

到目前为止,我发现我可以使用一个名为 supertest (https://github.com/visionmedia/superagent) 的库来测试我的路由,但是如果我破坏了我的路由和控制器,我该如何独立于它们的路由来测试我的控制器。

这是我的测试:

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,希望我可以注入它,但这并没有奏效。有没有办法模拟 res.send 对象?还是我走错了路?

【问题讨论】:

  • 您在响应对象上使用了哪些方法/属性?您到目前为止发布的代码似乎只使用请求对象并调用next
  • 嗨 Max,我正在使用 res.send,我将编辑并删除该注释代码,因为它具有误导性

标签: node.js unit-testing express


【解决方案1】:

当您测试您的路线时,您实际上并没有使用内置函数。比如说 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));
                }
       });
    });
});

您可以参考超级代理请求示例here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-02
    • 2020-08-12
    • 2017-06-26
    • 2011-12-01
    • 2014-01-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多