expressjsHow can I test my Express.js application?
Testing an Express.js application can be done using a variety of tools.
The most popular way is to use the supertest library. This library allows you to write test cases that make HTTP requests to your application and assert that the response is correct.
For example, with the following code you can test an endpoint that returns a JSON response:
const request = require('supertest');
const app = require('./app');
describe('GET /api/users', () => {
it('should return a list of users', (done) => {
request(app)
.get('/api/users')
.expect('Content-Type', /json/)
.expect(200)
.end((err, res) => {
if (err) return done(err);
expect(res.body).to.be.an('array');
done();
});
});
});
The code above:
- Requires the
supertestlibrary and the application. - Describes a test case for the endpoint
GET /api/users. - Makes a request to the endpoint with
request(app).get('/api/users'). - Asserts that the response has the correct Content-Type and status code.
- Asserts that the response body is an array.
Other popular tools for testing Express applications are mocha, chai and sinon.
Helpful links
More of Expressjs
- How do I use Express.js to upload a file to Amazon S3?
- How do I use Express.js to parse YAML files?
- How do I download a zip file using Express.js?
- How can I use Zipkin to trace requests in Express.js?
- How can I use the x-forwarded-for header in Express.js?
- How do I set up a YAML configuration file for a Node.js Express application?
- How do I set the time zone in Express.js?
- How can I disable the X-Powered-By header in Express.js?
- What is Express.js and how is it used for software development?
- What are the pros and cons of using Express.js vs Django according to Reddit users?
See more codes...