繁体   English   中英

单元测试Express控制器

[英]Unit Testing Express Controllers

我在多个方面都无法使用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很容易制作模型。 没那么多,我尝试抓住express.response,希望我可以注入它,但是没有用。 有没有一种方法可以模拟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));
                }
       });
    });
});

您可以在此处参考超级代理请求示例。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM