expressjsHow can I set up unit testing for an Express.js application?
Unit testing an Express.js application can be done using the popular testing framework Mocha. Mocha provides a simple way to set up tests for your application.
To get started, install Mocha using npm:
npm install --save-dev mocha
Then create a test
directory in your application root, and create a test file (e.g. test/app.test.js
) with the following content:
const assert = require('assert');
const request = require('supertest');
const app = require('../app');
describe('GET /', () => {
it('should return 200 OK', (done) => {
request(app)
.get('/')
.expect(200, done);
});
});
This test will ensure that a GET
request to the root /
route returns a 200 status code.
Finally, add a script to your package.json
file to run the tests:
"scripts": {
"test": "mocha"
}
Now you can run the tests from the command line with npm test
:
npm test
This will print out the results of the tests.
Helpful links
More of Expressjs
- How do I manage user roles in Express.js?
- How do I disable CORS in Express.js?
- How can I use express-zip js to zip and download files?
- How do I download a zip file using Express.js?
- How can I use an ExpressJS webhook to receive data from an external source?
- How can I use Zipkin to trace requests in Express.js?
- How do I use Express.js to handle asynchronous requests?
- What is Express.js and how is it used for software development?
- How do I use Zod with Express.js?
- How can I use Express.js to develop a web application?
See more codes...