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?
SuperTest is a Node. js library that helps developers test APIs. It extends another library called superagent, a JavaScript HTTP client for Node. js and the browser. Developers can use SuperTest as a standalone library or with JavaScript testing frameworks like Mocha or Jest.
Jest and SuperTest are both open source tools. Jest with 26.9K GitHub stars and 3.66K forks on GitHub appears to be more popular than SuperTest with 8.8K GitHub stars and 568 GitHub forks.
Axios is a very popular JavaScript library you can use to perform HTTP requests, that works in both Browser and Node. js platforms. It supports all modern browsers, including support for IE8 and higher. It is promise-based, and this lets us write async/await code to perform XHR requests very easily.
Axios: Axios is a Javascript library used to make HTTP requests from node. js or XMLHttpRequests from the browser and it supports the Promise API that is native to JS ES6. It can be used intercept HTTP requests and responses and enables client-side protection against XSRF. It also has the ability to cancel requests.
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);
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);
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With