How do I add Tests to this codebase?
This document outlines how to add tests to the benhall/express-demo
codebase.
Setting up the Test Environment
Install Testing Dependencies:
npm install --save-dev mocha chai supertest
- Mocha: A JavaScript test framework.
- Chai: An assertion library for writing expressive tests.
- Supertest: A library for testing HTTP requests.
Create a Tests Directory:
Create a directory named
tests
at the root level of your project.Create a Test File:
Create a JavaScript file within the
tests
directory (e.g.,app.test.js
).
Writing Tests
This section provides examples of how to write tests for various components of the codebase.
Testing the Index Route
// tests/app.test.js
const request = require('supertest');
const app = require('../app');
describe('GET /', () => {
it('responds with 200 status code', (done) => {
request(app)
.get('/')
.expect(200)
.end(done);
});
it('renders the index template', (done) => {
request(app)
.get('/')
.expect('Content-Type', /html/)
.end((err, res) => {
if (err) return done(err);
expect(res.text).to.contain('<h1>Express</h1>');
done();
});
});
});
Testing Error Handling
// tests/app.test.js
const request = require('supertest');
const app = require('../app');
describe('Error Handling', () => {
it('responds with 404 for non-existent route', (done) => {
request(app)
.get('/nonexistent-route')
.expect(404)
.end(done);
});
});
Running Tests
Add a Script to
package.json
:// package.json "scripts": { "test": "mocha tests" }
Run Tests:
npm run test
Ignoring Test Files
The nodemon.json
file already excludes the tests
directory. This prevents test files from being watched and restarted by Nodemon.
// nodemon.json
{
"verbose": true,
"ignore": ["tests/"]
}
Conclusion
This guide provides a basic framework for testing the benhall/express-demo
codebase. By incorporating tests, you can ensure the quality and stability of your application.