Tutorial: CRUD Express App built TDD

Sat, 23 Sep 2017

This tutorial expects a basic knowledge of command line/git/npm or yarn/js. Everything else I'll do my best to explain!


This tutorial will show how to build a CRUD (Create, Read, Update Delete) API built with Express and MongoDB. We'll go through all the required setup and build it Test Driven using Mocha and Chai.

Initial Setup

In a new project folder run yarn init. Answer all the questions or accept the default values. Once you've created your package.json, run yarn add express to add express to our dependencies.

Testing Setup

Run yarn add mocha chai chai-http -D to install mocha and chai and save them as dev dependencies. Run mkdir ./test then touch ./test/server.spec.js then open it in your text editor.

//chai is the testing library that we'll be using
const chai = require('chai');
const chaiHttp = require('chai-http');
const server = require('../app/server');
const should = chai.should();


describe('Todo API', () => {
  it('returns a message with status 200', (done) => {
      .end((err, res) => {
        res.body.message.should.equal('Hello World');

Add the following script to your package.json "test": "./node_modules/.bin/mocha --reporter spec" You should now be able to run yarn run test although you'll see an error as we haven't created the server file that we require.

Making the test pass

Run mkdir ./app then touch ./app/server.js to create a new file in our project root where we will create our express server. Open ./app/server.js in your IDE or text editor (I use VS Code).

//require express
const app = require("express")();

//define a port
const PORT = 3000;

//define a route
app.get('/', (req, res) => {
  res.send({message: 'Hello World'});

//launch the server and console.log
app.listen(PORT, () => {
  console.log('Server running on port:', PORT);

module.exports = app;

Add the following script to your package.json "start": "node ./app/server.js" You should now be able to run yarn start and see your server running on http://localhost:3000

If you run yarn run test our tests should now be passing too!

Pat yourself on the back, you now have a fully tested express server. It doesn't do much yet but next we'll work on creating a route to return some todos!



You can find the code for part 1 of this tutorial here. I've also added a few extra things like nodemon for hot reload.

Thanks for reading. Read another blog?