问题
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):
It manages starting and binding the app for you, making it available to receive the requests:
You may pass an
http.Server
, or aFunction
torequest()
- 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.
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