簡體   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