NodeJS中axios和supertest的区别

The difference between axios and supertest in NodeJS

Axios 和 Supertest 都可以向服务器发送 HTTP 请求。但是为什么Supertest是用来测试的,而Axios是用来练习API调用的呢?

因为Supertest provide some assertions API that axios not provide. So people usually using Supertest要进行 http 断言测试。

例如

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

使用 Supertest 而不是像 Axios(或 Superagent,Supertest 包装的 Superagent)这样的普通请求库有两个原因:

  1. 它为您管理应用程序的启动和绑定,使其可用于接收请求:

    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.

    否则,您必须启动应用程序并自行设置端口。

  2. 它增加了expect方法,它允许你在响应上做很多常见的断言,而不必自己写出来。例如,而不是:

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

    你可以写:

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