简体   繁体   English

Mocha如何公开节点控制器功能以测试脚本

[英]Mocha how to expose a node controller function to test script

Here is my foo-controller.js . 这是我的foo-controller.js

module.exports = function(params) {

    var router = require('express').Router();
    var db = params.db
    var controller = {};

    controller.getFoo = function (req, res) {
        // returns something
    }

    router.get('/foo', controller.getFoo);

    return router;

};

and here is my test.js . 这是我的test.js

var chai = require('chai');
var expect = require('chai').expect;
var bar = require('../api/controllers/bar/foo-controller');

console.log("Test", bar) // <- this returns the whole foo-controlelr.js

describe('Foo', function() {
    it('should blah blah', function() {

    });
});

But every time I to use bar.getFoo() <- the function I wanted to test. 但是每次我使用bar.getFoo() <-我想测试的功能。 It returns the error has no method 'getFoo' 它返回错误has no method 'getFoo'

Accessing the controller's getFoo function would require you to export this function via module.exports. 访问控制器的getFoo函数将要求您通过module.exports导出此函数。 But the code above does not export the controller but the router which is perfectly fine since the router is used to mount the router in express. 但是上面的代码不会导出控制器,而是导出路由器,因为路由器用于快速安装路由器,所以这很好。

For testing your controller you might split routing/route definition and controller in it's own modules: 为了测试您的控制器,您可以在自己的模块中拆分路由/路由定义和控制器:

foo-controller.js

module.exports = function(params) {
  var db = params.db
  var controller = {};

  controller.getFoo = function (req, res) {
    // returns something
  }
  return controller;

};

foo-router.js

var fooController = require('./foo-controller');

module.exports = function(params) {

  var router = require('express').Router();

  var controller = fooController(params);

  router.get('/foo', controller.getFoo);

  return router;
};

This enables you to test the controller without the router. 这使您可以在没有路由器的情况下测试控制器。

Another approach to test the code could be to do an "integration" test, testing the router and the controller together. 测试代码的另一种方法可能是进行“集成”测试,一起测试路由器和控制器。 Using a tool like supertest ( https://github.com/visionmedia/supertest ) you can write your integration test just like: 使用诸如supertest( https://github.com/visionmedia/supertest )之类的工具,您可以编写集成测试,如下所示:

var request = require('supertest');
var express = require('express');
var fooRouter = require('.path/to/router/foo');

describe('Foo', function() {
  it('should blah blah', function(done) {

    var app = express();

    app.use('/', fooRouter(params));

    request(app)
      .get('/foo')
      .expect(200)
      .end(function(err, res){
        if (err) throw err;
        done();
      });
    });
  });
});

The advantage of this approach is that your testing route definition plus controller. 这种方法的优点是您的测试路线定义加上控制器。

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

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