How to test API in an Express application using Jest and SuperTest

byGinkSun, 06 Feb 2022

1. Set up a new Express application

To set up a new Express application, you'll need to have Node.js and npm installed on your computer. Open a terminal and navigate to the directory where you want to create your Express application. Run the following command to create a new Express application:

npx express-generator my-api

This will create a new Express application called "my-api". Navigate into the application directory, and then install all the dependencies for the Express application:

cd my-api
npm install

2. Install Jest and SuperTest

To test the Express application, you'll need to install Jest and SuperTest. Jest is a popular JavaScript testing library, and SuperTest is a library for testing HTTP requests in Node.js.

In your terminal, run the following command to install Jest and SuperTest:

npm install jest supertest --save-dev

3. Write tests for your Express API

Create a new directory in your Express application called "tests". We'll put any test files in this directory.

Create a new file in the "tests" directory called "api.test.js". This is where you'll write the tests for your Express API using Jest and SuperTest.

In the "api.test.js" file, import the Express application and SuperTest:

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

Next, write a test to verify that the Express API returns a 200 OK response for a GET request to the root endpoint:

describe('GET /', () => {
  it('responds with 200 OK', async () => {
    const response = await request(app).get('/');
    expect(response.statusCode).toBe(200);
  });
});

4. Run the tests

npm pkg set scripts.test="jest"
npm run test

Jest will run the tests and display the results in the terminal. If all tests pass, you'll see a message indicating that all tests passed. If any tests fail, Jest will display an error message indicating which test failed and why.

This is a simple example of how to test an API in an Express application using Jest and SuperTest. You can expand on this example by writing tests for other endpoints in your API, testing for specific response data, and testing for error conditions.

By using Jest and SuperTest to test your Express API, you can ensure that your API is working as expected and catch bugs early in the development process.


© 2016-2024  GinkCode.com