Unit test express route calls controller method?

元气小坏坏 提交于 2020-01-04 16:59:11

问题


I see some similar questions, but my setup is slightly different and I can't figure out a good way to test this.

I'm trying to test that my express app routes are directed to the correct controller methods.

For example -

//server.js, base application

var express = require("express");
var app = express();
require("./routes.js")(app);
...

//routes.js
var menuController = require("./controllers/menu.js");

module.exports = function(expressApp) {
    expressApp.get('/menu', menuController.getMenu);
};
...

//test file
var express = require('express')
    , menuController = require("../../controllers/menu.js")
    , chai = require('chai')
    , should = chai.should()
    , sinon = require('sinon')
    , sinonChai = require("sinon-chai");
chai.use(sinonChai);

var app = express();
require("../../routes/routes.js")(app);

describe('routes.js', function(){

    it('/menu should call menuController.getMenu route', function(){
        var spy = sinon.spy(menuController, 'getMenu');
        app.get('/menu', spy);

        spy.should.have.been.called;  //fails, never called
    });

});  

How can I check to see that when calling app.get('/menu', ..), the callback from menuController is invoked? Or should I restructure the app somehow (I see a bunch of other ways to configure the routing)?


回答1:


Instead of doing that I would suggest checking the response code that comes back from /menu and also checking the response itself that it requals or contains a known response.




回答2:


It won't be truly unit test but you can do that, this way:

Use dependency injection like this:

function bootstrapRouterFactoryMethod(bootstrapController) {
    var router = express.Router();
    router.route('/').post(bootstrapController.bootstrap);
    return router;
};

module.exports = bootstrapRouterFactoryMethod;

And then pass fake as a bootstrapController and verify if bootstrap method is called.

var request = require('supertest');

...

it('calls bootstrapController #bootstrap', function (done) {
    var bootstrapControllerFake = {
        bootstrap: function(req, res) {
            done();
        }
    };
    var bootstrapRouter = bootstrapRouterFactoryMethod(bootstrapControllerFake);
    app.use(bootstrapRouter);
    request(app).post('/').end(function (err, res) {});
});


来源:https://stackoverflow.com/questions/28990887/unit-test-express-route-calls-controller-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!