An Introduction to SuperTest
SuperTest is a popular JavaScript library that simplifies testing HTTP servers and APIs. It sits on top of the superagent library, providing a high-level abstraction to make HTTP assertions straightforward and efficient. By leveraging the capabilities of superagent, SuperTest allows developers to conduct thorough testing while also offering the flexibility to access the lower-level API features when necessary.
About SuperTest
The primary objective of SuperTest is to make testing HTTP endpoints easy. It gives developers the tools to set up tests quickly and effectively, saving both time and effort while improving the reliability of their applications. Whether working with new or existing projects, SuperTest seamlessly integrates into development workflows.
Getting Started with SuperTest
To start using SuperTest, you need to install it as a development dependency in your Node.js project:
npm install supertest --save-dev
After installation, SuperTest can be easily included in your tests by requiring it:
const request = require('supertest');
Using SuperTest: Examples
SuperTest is versatile and can work with any test framework, although it can also be used standalone. Here is an example using Express (a popular web framework for Node.js):
const express = require('express');
const app = express();
app.get('/user', function(req, res) {
res.status(200).json({ name: 'john' });
});
request(app)
.get('/user')
.expect('Content-Type', /json/)
.expect('Content-Length', '15')
.expect(200)
.end(function(err, res) {
if (err) throw err;
});
Advanced Features
SuperTest also supports advanced features such as:
- HTTP2 Protocol: Enable this by appending an options object to
request
orrequest.agent
. - Authentication: Handle HTTP authentication easily using the
.auth()
method. - Error Handling: If an HTTP error occurs (responses that are not successful, i.e., non-2XX responses), it can be passed as the first argument in the callback if you do not specify an expected status code.
- Assertion Customization: Use
.expect()
to define custom assertions for verifying HTTP responses.
SuperTest with Mocha
Mocha, a test framework for node.js, is commonly used with SuperTest. Below is an example of a test case using Mocha:
describe('GET /user', function() {
it('responds with json', function(done) {
request(app)
.get('/user')
.set('Accept', 'application/json')
.expect('Content-Type', /json/)
.expect(200, done);
});
});
Promise and Async/Await Support
SuperTest supports promises and async/await syntax for a more modern and streamlined testing approach:
// Using Promises
describe('GET /users', function() {
it('responds with json', function() {
return request(app)
.get('/users')
.set('Accept', 'application/json')
.expect('Content-Type', /json/)
.expect(200)
.then(response => {
expect(response.body.email).toEqual('[email protected]');
});
});
});
// Using Async/Await
describe('GET /users', function() {
it('responds with json', async function() {
const response = await request(app)
.get('/users')
.set('Accept', 'application/json')
expect(response.headers["Content-Type"]).toMatch(/json/);
expect(response.status).toEqual(200);
expect(response.body.email).toEqual('[email protected]');
});
});
Assertions and Error Handling
SuperTest provides several methods for assertions:
.expect()
can assert various parts of the response, including status, body, and headers.- Custom assertion functions can be passed to
.expect(fn)
, allowing for detailed checks.
If an expectation fails, the error is returned to the callback of .end()
, which should be handled to ensure tests fail correctly when assertions do not meet the expected outcomes.
Conclusion
SuperTest stands as a robust and flexible tool for testing HTTP servers, simplifying the process with helpful abstractions while granting access to powerful underlying features when needed. Its compatibility with various test frameworks and support for modern JavaScript syntax make it an appealing choice for developers seeking efficient and effective API testing. Licensed under MIT, SuperTest openly encourages contributions and improvements from the developer community.