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 find Express.js tutorials on YouTube?
- How can I use express-zip js to zip and download files?
- How do I set the time zone in Express.js?
- How do I use Zod with Express.js?
- How can I use Zipkin to trace requests in Express.js?
- How can I use Express.js to yield results?
- How do I use adm-zip with Express.js?
- How can I use Express.js to make an XHR request?
- How do I use Express.js to handle x-www-form-urlencoded data?
- How can I use Express.js and Vite together for software development?
See more codes...