Skip to content

Instantly share code, notes, and snippets.

@cohenadair
Last active October 15, 2023 12:19
Show Gist options
  • Save cohenadair/f0452c86a6efdfcc5a89416ca6e23b43 to your computer and use it in GitHub Desktop.
Save cohenadair/f0452c86a6efdfcc5a89416ca6e23b43 to your computer and use it in GitHub Desktop.
How to quickly setup a Node.js REST API with Express, Mocha, and supertest.

tl;dr

  1. Download and install Node.js
  2. Download and extract the Sample Project
  3. In a Terminal window, navigate to the extracted folder
  4. Run npm install
  5. Run the app

Introduction

This guide is meant to be a very quick setup for a Node.js REST API. It will include links to each component if you'd like to read more.

Note that I use macOS, so the commands may be slightly different on a non-Unix machine.

Components

Environment Setup

Visual Studio Code (VSC) (optional)

Visual Studio Code is an awesome IDE with built in support for JavaScript, TypeScript, and Node.js debugging. This is completely optional, but it's the best free environment I've used.

Recommended Extensions

  1. Add jsdoc comments

Node.js

Download and install Node.js if it isn't already installed. You can run node --version in Terminal to verify installation.

Note that npm is packaged with Node.js. Run npm --version to verify.

TypeScript (optional)

TypeScript is optional, but I highly recommend using it for developing type-safe JavaScript applications.

  1. Install TypeScript by running npm install -g typescript
  2. Run tsc --version to verify installation.

Compile TypeScript files by running tsc for all TypeScript files, or tsc file.ts for a single file.

Project Setup

Home

  1. Create your project's directory folder by running mkdir my-app-name && cd my-app-name

  2. Initialize npm by running npm init and going through the prompts.

    Note that the package.json file that's created stores your app's dependencies. On a new computer, dependencies can be installed by running npm install from the same directory.

  3. If your IDE supports Node.js, install Node.js types: npm install @types/node --save

  4. If using TypeScript, run tsc --init and exclude node_modules in tsconfig.json

    {
        ...
        "exclude": [
            "node_modules"
        ]
    }
    

    This will ensure all Node dependencies are excluded from the tsc command.

Express

Express makes it incredibily easy to create a REST API in JavaScript.

Install express npm install express --save

Note that the --save flag is what save's it to your project's dependencies.

supertest (optional)

supertest used for unit testing server behaviour.

Install by running npm install supertest --save-dev

Mocha (optional)

Mocha is a great JavaScript unit testing framework. I highly recommend it.

  1. Install by running npm install mocha --save-dev
  2. If your IDE supports Node.js, install Mocha types: npm install @types/mocha --save-dev
  3. Add the following to package.json
    "scripts" : {
        "test: "mocha"
    }
    
  4. Add a test directory mkdir test
  5. Running npm test will give an error saying there are no test files found (expected).

Note that by default, Mocha will run all JavaScript files in the test/ directory.

Hello World!

Files

Add the following files to your project:

app.js

var express = require('express')
var app = express()

app.get('/', function (req, res) {
    res.send('Hello World!\n')
})

// Export server for testing.
var server = app.listen(3000);
module.exports = server;

test/app_tests.js

var request = require("supertest");
var assert = require('assert');

describe('array', function() {
    describe('#indexOf()', function() {
        it('should return -1 when the value is not present', function() {
            assert.equal(-1, [1,2,3].indexOf(4));
        });
    });
});

describe('routes', function() {
    var server;

    beforeEach(function() {
        // Clears the cache so a new server instance is used for each test.
        delete require.cache[require.resolve('../app')];
        server = require("../app");
    });

    afterEach(function() {
        server.close();
    });

    // Test to make sure URLs respond correctly.
    it("url /", function(done) {
        request(server)
            .get("/")
            .end(function(err, res) {
                assert.equal(res.text, "Hello World!\n");
                done();
            });
    });
});

Running the App

  1. Run node app.js
  2. Run curl localhost:3000 in a new Terminal window.
  3. Hello World! will print in the console.

Running the Test Suites

  1. If using TypeScript, run tsc on your project's root directory to compile all TypeScript files.
  2. Run npm test. The following will print in the Terminal window:
    > [email protected] test /Users/Cohen/node-app
    > mocha
    
    
    
    array
        #indexOf()
        ✓ should return -1 when the value is not present
    
    routes
        ✓ url /
    
    
    2 passing (141ms)
    

Conclusion

I strongly encourage your to read the documentation for the components used in the guide (see Components). They are all excellent and extremely easy to follow.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment