Getting Started with Node.js Unit Testing
Unit testing is crucial in Node.js applications to ensure the functionality of your routes and middleware. In an Express application, testing helps identify potential issues before deployment. In this guide, we will walk through setting up and writing unit tests for a Node.js application with Express using Mocha and Chai.
Setup:
First, ensure you have a Node.js project with Express. If you don’t have one, you can create it using:
1 2 |
npm init -y npm install express |
Mocha is a test framework, Chai provides assertion methods, and Supertest is used for testing HTTP requests. install the testing libraries:
1 |
npm install mocha chai supertest --save-dev |
Writing Your First Test
Let’s create a simple Express route and write a test for it. In app.js
, define a route:
1 2 3 4 5 6 7 8 |
const express = require('express'); const app = express(); app.get('/hello', (req, res) => { res.status(200).send('Hello, World!'); }); module.exports = app; |
Now, in test/app.test.js
, write the test:
1 2 3 4 5 6 7 8 9 10 11 |
const request = require('supertest'); const app = require('../app'); const { expect } = require('chai'); describe('GET /hello', () => { it('should return Hello, World!', async () => { const res = await request(app).get('/hello'); expect(res.status).to.equal(200); expect(res.text).to.equal('Hello, World!'); }); }); |
Here, request
sends a GET request to the /hello
route. The test checks if the response status is 200
and the returned text matches 'Hello, World!'
.
Running Tests
Now, run the tests with:
1 |
mocha |
Conclusion
Unit testing in Node.js with Express is straightforward when using Mocha, Chai, and Supertest. By writing unit tests, you ensure the reliability of your application and reduce potential bugs. So, always include testing in your development workflow!