# Testing

# Introduction

Testing is considered an essential part of software development. This helps ensure that releases meet quality and performance goals. Testing helps provides a faster feedback loop to developers which increases the productivity of the individual developers.

ExpressWebJs support many javascript testing packages, but by default it supports Jest.

Jest is a JavaScript test runner, that is, a JavaScript library for creating, running, and structuring tests. Jest ships as an NPM package, you can install it in any JavaScript or Typescript project. Jest is one of the most popular test runner these days.

# Installation

To get started, first install the package

npm i --save-dev @types/jest jest supertest

Let's also configure an NPM script for running our tests from the command line. Open up package.json and configure a script named test for running Jest in the script section:

"scripts": {
    "test": "jest"
  },

Once that is done, we can create a __test__ folder in our root directory to house all our application test.

# Unit testing

In the following example, we test two an endpoint which will communicate with the route, controller, down to the service. As mentioned, Jest is provided as the default testing framework. It serves as a test-runner and also provides assert functions and test-double utilities that help with mocking, spying, etc. In the following basic test.

import supertest from "supertest";

let Route = supertest("http://127.0.0.1:5100/api/city");

it("Get a city", async (done) => {
  await Route.get("/get_city/277d04e7-2185-4d6b-92d5-4df454958df0")
    .set("Content-type", "application/json")
    .expect(200)
    .then((response) => {
      // Check the response data
      expect(response.body).toBeTruthy();
      // Check the response data payload
      expect(response.body["payload"]).toBeTruthy();
    });

  done();
});
💡 Learn more about Jest features here.