Express Server Mechanics: Routing, Middleware, and Approaches to Testing
express serverapp.get('/thing', (req,res) => {})(req,..)app.get('/api/:thing',...) = req.params.thinghttp://server/route?ball=round = req.query.ball(..., res)send() and status() that Express uses to format the output to the browser properly
request, response and next as parametersMiddleware runs your code, and then runs the next() middleware in the series.
function myLogger(req,res,next) {
console.log(req.method);
next(); // runs the next middleware in line
}
If you call next() with an argument, it’ll skip all remaining middleware and run your error handler, with that argument as the error
function loggedIn(req,res,next) {
if( validUser ) { next(); } // Run the next middleware
else { next("you need to login"); } // Run the error handler, skipping all other middleware
}
Your route handler (your normal
(req,res)function) is always the last middleware in the series!
supertest to run your tests
server.js
const express = require('express');
const app = express();
app.get('/data', (req,res) => res.json({}));
// Export an object with the "app" in it.
module.exports = {
start: () => app.listen(3000),
server: app
}
server.test.js
const supertest = require('supertest');
const myServer = require('server.js');
const client = supertest(myServer.server);
describe('my server', () => {
test('can send data', () => {
return client.get('/data')
.then( response => {
expect(response.body).toBeDefined();
})
})
})
npm install jestAdd the proper “testing scripts” to your package.json file
"scripts": {
"test": "jest --coverage",
"watch": "jest --coverage --watchAll"
}
npm testnpm run watch