Testing backend route handlers with Jest


Singletoning database object

Singleton pattern

The singleton pattern is a software design pattern that restricts the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system.

Setting up MongoDB in app.locals

app.locals is an object that contains local variables scoped to the application, and therefore available to all the routes. We can use it to store the database object.

Please add the following code to app.js right before module.exports = app;:

const { MongoClient } = require("mongodb");
// Replace the uri string with your connection string.
const uri = "mongodb+srv://<username>:<password>@<endpoint>.mongodb.net/?retryWrites=true&w=majority";
const client = new MongoClient(uri);
app.locals.db = client.db('bookingDB');

app.locals.saltRounds = 10;

// You may also initialize the database with some data here
// (async () => {
//     const salt = bcrypt.genSaltSync(app.locals.saltRounds);
//     const hash = bcrypt.hashSync('123456', salt);
//     let result = await app.locals.db.collection("users").insertOne({
//         username: 'admin',
//         password: hash,
//         role:'admin'
//     })
// })();

module.exports = app;

Accessing database object in route handlers

After setting up the database object in app.locals, we can access it in route handlers. For example, we can use it to query the database in POST /api/login route handler:

const bcrypt = require('bcrypt')
const jwt = require('jsonwebtoken')
router.post('/api/login', async function (req, res, next) {
  let user = req.body;
  try {
    let result = await req.app.locals.db.collection("users").findOne({
      username: user.username,
    });
    if (result) {
      if (bcrypt.compareSync(user.password, result.password)) {
        delete result.password;
        result.token = jwt.sign(
          { result },
          "process.env.TOKEN_KEY",
          { expiresIn: "1h" }
        );
        return res.status(200).json(result);
      }
      return res.status(401).json({ message: "Incorrect password" });
    }
    return res.status(401).json({ message: "User not found" });

  } catch (error) {
    console.error(error)
    return res.status(500).json(error);
  }
});

Documenting APIs using Postman

Create a new collection

To create a new collection, click on the Create new button on the top left corner of the Postman app.

Add a new request

To add a new request, click on the Add button on the top right corner of the Postman app.

Export APIs and convert to OpenAPI specification

To export APIs, click on the Export button on the top right corner of the Postman app.

Convert to OpenAPI with Postman-to-OpenAPI

We will use postman-to-openapi to convert postman collection to OpenAPI specification. Let’s install it globally (You may need to run with sudo in Mac/Linux).

npm install -g postman-to-openapi

After installation, we can convert the postman collection to OpenAPI specification with the following command:

p2o postman_collection.json -f openapi.yaml

Getting started with Jest and supertest

Jest is a JavaScript testing framework designed to ensure correctness of any JavaScript codebase. It allows you to write tests with an approachable, familiar and feature-rich API that gives you results quickly.

jest-openapi is a Jest extension that allows you to test your OpenAPI specification against your API implementation. It provides a set of Jest matchers that you can use to test your API implementation against your OpenAPI specification.

Install dependencies

Besides Jest, we will also use supertest to test HTTP requests. Let’s install them with the following command:

npm install --save-dev jest jest-openapi supertest

Initialize Jest

Let’s initialize Jest with the following command:

npx jest --init

Example

</details>

Configuration

Let’s take a look to jest.config.js, which is the configuration file for Jest genereated by the CLI.

/*
 * For a detailed explanation regarding each configuration property, visit:
 * https://jestjs.io/docs/configuration
 */

module.exports = {
  // All imported modules in your tests should be mocked automatically
  // automock: false,

  // Stop running tests after `n` failures
  // bail: 0,

  // The directory where Jest should store its cached dependency information
  // cacheDirectory: "/tmp/jest_rs",

  // Automatically clear mock calls, instances, contexts and results before every test
  // clearMocks: false,

  // Indicates whether the coverage information should be collected while executing the test
  // collectCoverage: false,

  // An array of glob patterns indicating a set of files for which coverage information should be collected
  // collectCoverageFrom: undefined,

  // The directory where Jest should output its coverage files
  // coverageDirectory: undefined,

  // An array of regexp pattern strings used to skip coverage collection
  // coveragePathIgnorePatterns: [
  //   "/node_modules/"
  // ],

  // Indicates which provider should be used to instrument code for coverage
  coverageProvider: "v8",

  // A list of reporter names that Jest uses when writing coverage reports
  // coverageReporters: [
  //   "json",
  //   "text",
  //   "lcov",
  //   "clover"
  // ],

  // An object that configures minimum threshold enforcement for coverage results
  // coverageThreshold: undefined,

  // A path to a custom dependency extractor
  // dependencyExtractor: undefined,

  // Make calling deprecated APIs throw helpful error messages
  // errorOnDeprecated: false,

  // The default configuration for fake timers
  // fakeTimers: {
  //   "enableGlobally": false
  // },

  // Force coverage collection from ignored files using an array of glob patterns
  // forceCoverageMatch: [],

  // A path to a module which exports an async function that is triggered once before all test suites
  // globalSetup: undefined,

  // A path to a module which exports an async function that is triggered once after all test suites
  // globalTeardown: undefined,

  // A set of global variables that need to be available in all test environments
  // globals: {},

  // The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers.
  // maxWorkers: "50%",

  // An array of directory names to be searched recursively up from the requiring module's location
  // moduleDirectories: [
  //   "node_modules"
  // ],

  // An array of file extensions your modules use
  // moduleFileExtensions: [
  //   "js",
  //   "mjs",
  //   "cjs",
  //   "jsx",
  //   "ts",
  //   "tsx",
  //   "json",
  //   "node"
  // ],

  // A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module
  // moduleNameMapper: {},

  // An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader
  // modulePathIgnorePatterns: [],

  // Activates notifications for test results
  // notify: false,

  // An enum that specifies notification mode. Requires { notify: true }
  // notifyMode: "failure-change",

  // A preset that is used as a base for Jest's configuration
  // preset: undefined,

  // Run tests from one or more projects
  // projects: undefined,

  // Use this configuration option to add custom reporters to Jest
  // reporters: undefined,

  // Automatically reset mock state before every test
  // resetMocks: false,

  // Reset the module registry before running each individual test
  // resetModules: false,

  // A path to a custom resolver
  // resolver: undefined,

  // Automatically restore mock state and implementation before every test
  // restoreMocks: false,

  // The root directory that Jest should scan for tests and modules within
  // rootDir: undefined,

  // A list of paths to directories that Jest should use to search for files in
  // roots: [
  //   "<rootDir>"
  // ],

  // Allows you to use a custom runner instead of Jest's default test runner
  // runner: "jest-runner",

  // The paths to modules that run some code to configure or set up the testing environment before each test
  // setupFiles: [],

  // A list of paths to modules that run some code to configure or set up the testing framework before each test
  // setupFilesAfterEnv: [],

  // The number of seconds after which a test is considered as slow and reported as such in the results.
  // slowTestThreshold: 5,

  // A list of paths to snapshot serializer modules Jest should use for snapshot testing
  // snapshotSerializers: [],

  // The test environment that will be used for testing
  // testEnvironment: "jest-environment-node",

  // Options that will be passed to the testEnvironment
  // testEnvironmentOptions: {},

  // Adds a location field to test results
  // testLocationInResults: false,

  // The glob patterns Jest uses to detect test files
  // testMatch: [
  //   "**/__tests__/**/*.[jt]s?(x)",
  //   "**/?(*.)+(spec|test).[tj]s?(x)"
  // ],

  // An array of regexp pattern strings that are matched against all test paths, matched tests are skipped
  // testPathIgnorePatterns: [
  //   "/node_modules/"
  // ],

  // The regexp pattern or array of patterns that Jest uses to detect test files
  // testRegex: [],

  // This option allows the use of a custom results processor
  // testResultsProcessor: undefined,

  // This option allows use of a custom test runner
  // testRunner: "jest-circus/runner",

  // A map from regular expressions to paths to transformers
  // transform: undefined,

  // An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation
  // transformIgnorePatterns: [
  //   "/node_modules/",
  //   "\\.pnp\\.[^\\/]+$"
  // ],

  // An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them
  // unmockedModulePathPatterns: undefined,

  // Indicates whether each individual test should be reported during the run
  // verbose: undefined,

  // An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode
  // watchPathIgnorePatterns: [],

  // Whether to use watchman for file crawling
  // watchman: true,
};

Adding tests directory to the project

We will add a directory called tests to the root of the project. This directory will contain all the tests for the project.

mkdir tests

After that, please modify jest.conf.js file to include the tests directory.

module.exports = {
  // ...
  roots: ["<rootDir>/tests"],
  // ...
};

Writing the first test

Let’s write the first test for the project. Create a file called tests/index.test.js and add the following code. This test will check if the server is running and responding to the GET request on the root path.

const app = require('../app')
const request = require('supertest')

describe("Test the root path /", () => {
  test("It should response the GET method", async () => {
    const response = await request(app).get("/");
    expect(response.statusCode).toBe(200);
  });
});

Running the test

To run the test, execute the following command.

npm test

Testing OpenAPI specification

Let’s write a test to check if the OpenAPI specification is valid. Create a file called tests/login.test.js and add the following code.

// Import this plugin
const jestOpenAPI = require('jest-openapi').default;
const request = require('supertest')
const app = require('../app')
const bcrypt = require('bcrypt');
const { ObjectId } = require('mongodb');
const path = require('path')

// Load an OpenAPI file (YAML or JSON) into this plugin
jestOpenAPI(path.join(__dirname, '../openapi.yaml'));

// Write your test
describe('POST /api/login', () => {
    const adminUsername = 'testingAdmin';
    const adminPassword = '123456'
    let adminUserId = '';
    
    const { MongoClient } = require("mongodb");
    // Replace the uri string with your connection string.
    const uri = "mongodb+srv://<username>:<password>@<endpoint>.mongodb.net/?retryWrites=true&w=majority";
    const client = new MongoClient(uri);
    const db = client.db('bookingDB');
    const saltRounds = 10;

    beforeAll(async () => {
        const salt = bcrypt.genSaltSync(saltRounds)
        let result = await db.collection('users').insertOne({
            username: adminUsername,
            password: bcrypt.hashSync(adminPassword, salt),
            role: 'admin'
        })
        adminUserId = result.insertedId
    });

    it('should satisfy OpenAPI spec', async () => {
        // Post username password json to login API
        const res = await request(app).post("/api/login").send({
            username: adminUsername,
            password: adminPassword
        });

        // Assert that the HTTP response satisfies the OpenAPI spec
        expect(res).toSatisfyApiSpec();
    });

    afterAll(async () => {
        await db.collection('users').deleteOne({_id: new ObjectId(adminUserId)})
    });
});

Running the test

To run the test, execute the following command.

npm test

asciicast