DEV Community

akshaiim
akshaiim

Posted on

Implement testing in node-express apis using jest and supertest

Testing is important to verify the behavior of the smallest parts of code in your application. It helps improve the quality of your code and reduces the amount of time and money you spend on bug fixing. Moreover, unit testing helps you find bugs early on in the development life cycle. In Node.js there are many frameworks available for running unit tests. Some of them are:
Mocha, Jest, Jasmine etc.

we'll be looking at unit testing via jest and supertest below:

Jest is a popular testing framework. It is developed and maintained by Facebook. One of the key features of jest is it is well documented, and it supports parallel test running i.e. each test will run in their own processes to maximize performance. It also includes several features like test watching, coverage, and snapshots.

You can install it using the following command:

npm install --save-dev jest

By default, Jest expects to find all the test files in a folder called “tests” in your root folder.

Example of a test using jest:

const sum = require('./sum');

test('adds 1 + 2 to equal 3', () => {
expect(sum(1, 2)).toBe(3);
});
Enter fullscreen mode Exit fullscreen mode

Following are some assert types supported by jest:

toBe
eg: expect(2+2).toBe(4),
toEqual
eg:- expect(data).toEqual({one: 1, two: 2})
not.toBe
eg:- expect(2+2).not.toBe(5)
toBeNull, toBeUndefined, toBegreaterThan, toBeLessThan, toContain, toMatch etc.

following command can be used to run individual file

jest <test file name>

script to run all test files in test folder to be added in package.json

"test": "jest"

npm test can be used to run the tests

Api endpoint testing can be done with the help of jest and another library called supertest.

install supertest using
npm install --save-dev supertest

A sample api test can be implemented as shown below in test folder.

const request = require('supertest')
const app = require('./app')
const baseUrl = 'http://localhost:8000'

describe('sends users', (app) => {
  it('should return users', async () => {
    const res = await request(baseUrl)
      .get('/getUsers');
    expect(res.statusCode).toEqual(200);
    expect(res.body).toHaveProperty('users');
  });
});

describe('Post Endpoints', () => {
  it('should create a new post', async () => {
    const res = await request(baseUrl)
      .post('/posts')
      .send({
        userId: 1,
        title: 'test',
      })
    expect(res.statusCode).toEqual(200)
    expect(res.body).toHaveProperty('post')
  })
})

Enter fullscreen mode Exit fullscreen mode

Run the tests using npm test and Test results can be seen in terminal console as seen below:

Image description

For More Info, Visit:
https://jestjs.io/
https://www.npmjs.com/package/supertest

Oldest comments (0)