Wednesday 23 March 2016

Structuring Express applications with unit testing in mind?

Diving into node at work to build a REST API with express. I've separated the route logic like follows, however I'm having an issue with unit testing because most of my functions are "private" in their controllers:// app.js // -------------------------------------- var userRoutes = require('./routes/users'); app.use('/users', userRoutes); // routes/users.js // -------------------------------------- var express = require('express'); var router = express.Router(); var usersController = require('../controllers/users'); router.get('/', usersController.getAll); // no logic in this file, all logic in controller actions module.exports = router // controllers/users.js // -------------------------------------- module.exports.getAll = (req, res) => { if (someFunction()) { res.sendStatus(200); } else { res.sendStatus(500); } } function someFunction() { // function that I want to test } This seems organized and if fulfills my OCD, but it means that I can't unit test someFunction() because it doesn't get exported.The solution that I was thinking about was to put all "express" centered logic in the routes file and export all the functions in the controller. So the changes would look like:// routes/users.js // -------------------------------------- var express = require('express'); var router = express.Router(); var usersController = require('../controllers/users'); router.get('/', (req, res) => { if (usersController.someFunction()) { res.sendStatus(200); } else { res.sendStatus(500); } }); module.exports = router // controllers/users.js // -------------------------------------- module.exports.someFunction = () => { // function that I want to test } This means that I could import the controller actions and test them directly with mocha, however it doesn't feel as clean to me because now there is logic in the route files.What do you all think? What patterns do you all follow? Very curious to hear :)

Submitted March 24, 2016 at 01:47AM by ProceedsNow

No comments:

Post a Comment