The difference between axios and supertest in NodeJS

Viewed 4941

Both Axios and Supertest can send HTTP requests to a server. But why is Supertest used for testing while Axios is used for practice API calls?

2 Answers

There are two reasons to use Supertest rather than a vanilla request library like Axios (or Superagent, which Supertest wraps):

  1. It manages starting and binding the app for you, making it available to receive the requests:

    You may pass an http.Server, or a Function to request() - if the server is not already listening for connections then it is bound to an ephemeral port for you so there is no need to keep track of ports.

    Without this, you'd have to start the app and set the port yourself.

  2. It adds the expect method, which allows you to make a lot of common assertions on the response without having to write it out yourself. For example, rather than:

    // manage starting the app somehow...
    
    axios(whereAppIs + "/endpoint")
      .then((res) => {
        expect(res.statusCode).toBe(200);
      });
    

    you can write:

    request(app)
      .get("/endpoint")
      .expect(200);
    

Because Supertest provide some assertions API that axios not provide. So people usually using Supertest to doing http assertion testing.

e.g.

const request = require('supertest');

describe('GET /user', function() {
 it('responds with json', function(done) {
   request(app)
     .get('/user')
     .auth('username', 'password')
     .set('Accept', 'application/json')
     .expect('Content-Type', /json/)
     .expect(200, done);
 });
});
Related