Express

Overview

Express Server Mechanics: Routing, Middleware, and Approaches to Testing

Class Outline

Learning Objectives

Students will be able to

Describe and Define

Execute

Notes

Express Routing

Express Middleware

Middleware 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!

Server Testing

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();
      })
  })
})

Setup for Testing

  1. Install “Jest” so that you can run your tests npm install jest
  2. Add the proper “testing scripts” to your package.json file

    "scripts": {
      "test": "jest --coverage",
      "watch": "jest --coverage --watchAll"
    }
    
  3. Run your tests on demand
    • npm test
  4. Run your tests automatically as you save your files1
    • npm run watch