How to mock request and response in nodejs to test middleware/controllers?

后端 未结 6 701
花落未央
花落未央 2021-02-01 14:37

My application has several layers: middleware, controllers, managers. Controllers interface is identical to middlewares one: (req, res, next).

So my question is: how ca

6条回答
  •  孤独总比滥情好
    2021-02-01 15:30

    A bit old post, but I would like to give my 2 cents. The approach you want to take depends on whether you are doing unit testing or integration testing. If you are going down the route of using supertest, that means you are running the actual implementation code and that means you are doing integration testing. If that's what you want to do this approach is fine.

    But if you are doing unit testing, you would mock req and res objects (and any other dependencies involved). In the below code (non-relevant code removed for brevity), I am mocking res and giving just a mock implementation of json method, as that's the only method I need for my tests.

    // SUT
    kids.index = function (req, res) {
    if (!req.user || !req.user._id) {
        res.json({
            err: "Invalid request."
        });
    } else {
        // non-relevent code
    }
    };
    
    // Unit test
    var req, res, err, sentData;
    describe('index', function () {
    
        beforeEach(function () {
            res = {
                json: function (resp) {
                    err = resp.err;
                    sentData = resp.kids;
                }
            };
        });
        it("should return error if no user passed in request", function () {
            req = {};
    
            kidsController.index(req, res);
            expect(err).to.equal("Invalid request.");
    
        });
    
        /// More tests....
    })
    

提交回复
热议问题