如何单元测试表达路由器的路由 [英] How to unit test express Router routes

查看:159
本文介绍了如何单元测试表达路由器的路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Node和Express的新手,我正在尝试对我的路由/控制器进行单元测试。我把我的路线与我的控制器分开了。如何测试我的路线?

I'm new to Node and Express and I'm trying to unit test my routes/controllers. I've separated my routes from my controllers. How do I go about testing my routes?

config / express.js

  var app = express();
  // middleware, etc
  var router = require('../app/router')(app);

app / router / index.js

  module.exports = function(app) {
    app.use('/api/books', require('./routes/books'));
  };

app / router / routes / books.js

  var controller = require('../../api/controllers/books');
  var express = require('express');
  var router = express.Router();

  router.get('/', controller.index);

  module.exports = router;

app / api / controllers / books.js

// this is just an example controller
exports.index = function(req, res) {
    return res.status(200).json('ok');
};

app / tests / api / routes / books.test.js

  var chai = require('chai');
  var should = chai.should();
  var sinon = require('sinon');

  describe('BookRoute', function() {

  });


推荐答案

代码:

config / express.js

var app = express();
// middleware, etc
var router = require('../app/router')(app);

module.exports = app;

app / tests / api / routes / books.test.js

var chai = require('chai');
var should = chai.should();
var sinon = require('sinon');
var request = require('supertest');
var app = require('config/express');

describe('BookRoute', function() {
    request(app)
        .get('/api/books')
        .expect('Content-Type', /json/)
        .expect('Content-Length', '4')
        .expect(200, "ok")
        .end(function(err, res){
           if (err) throw err;
        });
});

注意事项:

如果您的服务器需要在一组测试开始时的初始状态(因为你正在执行改变服务器状态的调用),你需要编写一个函数来返回一个新配置的应用程序和每组测试的开始。有一个NPM库: https://github.com/bahmutov/really-need 允许您需要一个新实例化的服务器版本。

If your server requires an initial state at the beginning of a set of tests (because you're executing calls which mutate server state), you'll need to write a function that will return a freshly configured app and the beginning of each group of tests. There is an NPM library: https://github.com/bahmutov/really-need that will allow you to require a freshly instantiated version of your server.

这篇关于如何单元测试表达路由器的路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆