简体   繁体   English

单元测试Express控制器

[英]Unit Testing Express Controllers

I am having trouble unit testing with Express on a number of fronts, seems to be a lack of documentation and general info online about it. 我在多个方面都无法使用Express进行单元测试,似乎缺少有关它的文档和常规信息。

So far I have found out I can test my routes with a library called supertest ( https://github.com/visionmedia/superagent ), but what if I have broken my routes and controllers up, how can I go about testing my controllers independently of their routes. 到目前为止,我发现我可以使用名为supertest( https://github.com/visionmedia/superagent )的库来测试我的路由,但是如果我中断了路由和控制器该怎么办,我该如何测试我的控制器呢?与他们的路线无关。

here is my test: 这是我的测试:

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 is easy enough to mockup. req很容易制作模型。 res not so much, I tried grabbing express.response, hoping I could just inject it but this hasn't worked. 没那么多,我尝试抓住express.response,希望我可以注入它,但是没有用。 Is there a way to simulate the res.send object? 有没有一种方法可以模拟res.send对象? Or am I going the wrong way about this? 还是我走错路了?

When you are testing your routes, you don't actually use the inbuilt functions. 在测试路线时,实际上并没有使用内置函数。 Say for example, ProductController.create(req, res); 举例来说,ProductController.create(req,res);

What you basically need to do is, run the server on a port and send a request for each url. 您基本上需要做的是,在端口上运行服务器,并为每个URL发送一个请求。 As you mentioned supergent, you can follow this code. 正如您提到的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));
                }
       });
    });
});

You can refer to superagent request examples here . 您可以在此处参考超级代理请求示例。

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

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