The difference between axios and supertest in NodeJS

孤街醉人 提交于 2021-01-27 19:17:07

问题


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?


回答1:


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);
    



回答2:


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);
 });
});


来源:https://stackoverflow.com/questions/62991474/the-difference-between-axios-and-supertest-in-nodejs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!