javascript - How to unit test express Router routes -
i'm new node , express , i'm trying unit test routes/controllers. i've separated routes controllers. how go testing 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
// 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() { });
code:
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; }); });
considerations:
if server requires initial state @ beginning of set of tests (because you're executing calls mutate server state), you'll need write function return freshly configured app , beginning of each group of tests. there npm library: https://github.com/bahmutov/really-need allow require freshly instantiated version of server.
Comments
Post a Comment