本文介绍了单元测试快速路由调用控制器方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我看到了一些类似的问题,但是我的设置略有不同,我想不出一个很好的方法来测试这一点.

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.

例如-

//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
    });

});

当调用app.get('/menu',..)时,如何检查是否调用了menuController的回调?还是应该以某种方式重组应用程序(我看到了许多其他配置路由的方法)?

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)?

推荐答案

这并不是真正的单元测试,但是您可以通过以下方式做到这一点:

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

像这样使用依赖注入:

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

module.exports = bootstrapRouterFactoryMethod;

然后将假参数作为bootstrapController传递,并验证是否调用了bootstrap方法.

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) {});
});

这篇关于单元测试快速路由调用控制器方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-07 01:42