Skip to main content

Express Test Reporting

When building Express.js applications, running tests is only half the battle. Understanding test results, tracking failures, and sharing results with your team are equally important aspects of the testing process. This is where test reporting comes in.

What is Test Reporting?

Test reporting is the process of generating structured output from your test runs that can be easily analyzed, shared, and tracked over time. Good test reports help you:

  • Quickly identify which tests failed and why
  • Track test performance over time
  • Share test results with team members
  • Integrate testing into CI/CD pipelines
  • Generate documentation on test coverage

Setting Up Basic Test Reporting

Let's start with setting up basic test reporting for Express applications. We'll cover both popular testing frameworks: Jest and Mocha.

Jest Reporting

Jest comes with a built-in reporter that provides useful information in the console. To run tests with Jest:

bash
npx jest

This will show a summary of passed and failed tests in the terminal.

For more detailed reporting, you can use the --verbose flag:

bash
npx jest --verbose

Custom Reports with Jest

Jest supports various reporting options through its configuration. Create or modify your jest.config.js file:

javascript
module.exports = {
reporters: [
'default',
['jest-junit', {
outputDirectory: 'reports',
outputName: 'jest-junit.xml',
}]
],
};

To use this configuration, first install the required package:

bash
npm install --save-dev jest-junit

Now when you run Jest, it will generate both the default console output and an XML report in the reports directory.

Mocha Reporting

If you're using Mocha with Express, you can specify different reporters when running tests:

bash
npx mocha --reporter spec

Other built-in reporters include:

  • dot: minimal output with dots
  • nyan: the famous Nyan Cat reporter
  • landing: airplane landing view
  • json: JSON output for programmatic use
  • html: HTML report

Example of generating an HTML report:

bash
npx mocha --reporter html > report.html

Advanced Test Reporting

As your application grows, you might need more sophisticated reporting options.

HTML Reports for Visual Analysis

HTML reports provide a visual way to analyze test results.

For Jest, you can use jest-html-reporter:

bash
npm install --save-dev jest-html-reporter

Update your Jest configuration:

javascript
module.exports = {
reporters: [
'default',
['jest-html-reporter', {
pageTitle: 'Express API Test Report',
outputPath: './reports/test-report.html',
}]
],
};

Code Coverage Reports

Code coverage reports show how much of your code is covered by tests.

For Jest:

bash
npx jest --coverage

This creates a coverage directory with detailed HTML reports.

For Mocha with Istanbul:

bash
npm install --save-dev nyc

Then update your test script in package.json:

json
{
"scripts": {
"test": "nyc --reporter=html --reporter=text mocha"
}
}

Real-world Example: API Test Reporting

Let's look at a real-world example of test reporting for an Express API. We'll create tests for a simple user API and generate reports.

First, here's our Express route:

javascript
// routes/users.js
const express = require('express');
const router = express.Router();

router.get('/', (req, res) => {
res.json([
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' }
]);
});

router.get('/:id', (req, res) => {
const id = parseInt(req.params.id);
if (id === 1) {
return res.json({ id: 1, name: 'Alice' });
} else if (id === 2) {
return res.json({ id: 2, name: 'Bob' });
}
res.status(404).json({ error: 'User not found' });
});

module.exports = router;

Now, let's write tests with Jest and supertest:

javascript
// __tests__/users.test.js
const request = require('supertest');
const express = require('express');
const usersRouter = require('../routes/users');

const app = express();
app.use('/users', usersRouter);

describe('User API', () => {
test('GET /users returns list of users', async () => {
const response = await request(app).get('/users');
expect(response.status).toBe(200);
expect(response.body).toHaveLength(2);
expect(response.body[0]).toHaveProperty('name', 'Alice');
});

test('GET /users/:id returns specific user', async () => {
const response = await request(app).get('/users/1');
expect(response.status).toBe(200);
expect(response.body).toHaveProperty('name', 'Alice');
});

test('GET /users/:id returns 404 for non-existent user', async () => {
const response = await request(app).get('/users/999');
expect(response.status).toBe(404);
});
});

To generate a complete report, run:

bash
npx jest --coverage

Sample output:

PASS  __tests__/users.test.js
User API
✓ GET /users returns list of users (15 ms)
✓ GET /users/:id returns specific user (3 ms)
✓ GET /users/:id returns 404 for non-existent user (2 ms)

----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 100 | 100 |
users.js | 100 | 100 | 100 | 100 |
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 3 passed, 3 total
Snapshots: 0 total
Time: 0.966 s, estimated 1 s

Integrating with CI/CD Pipelines

Test reports are especially valuable in continuous integration environments. Here's how to set up reporting in popular CI systems:

GitHub Actions Example

yaml
# .github/workflows/test.yml
name: Run Tests

on: [push, pull_request]

jobs:
test:
runs-on: ubuntu-latest

steps:
- uses: actions/checkout@v2
- name: Use Node.js
uses: actions/setup-node@v2
with:
node-version: '16'
- name: Install dependencies
run: npm ci
- name: Run tests
run: npm test
- name: Upload test results
uses: actions/upload-artifact@v2
with:
name: test-reports
path: |
reports/
coverage/

Best Practices for Test Reporting

  1. Include reporting in CI/CD pipelines: Make test reporting an integral part of your continuous integration process.

  2. Track trends over time: Don't just look at individual reports—track how your test coverage and pass/fail rates change over time.

  3. Make reports accessible: Ensure everyone on your team can easily access and understand test reports.

  4. Set up notifications: Configure alerts for when test coverage drops or new failures appear.

  5. Integrate with issue tracking: Link test failures to tickets in your issue tracking system.

Summary

Test reporting is an essential part of a mature testing strategy for Express applications. By generating clear, comprehensive reports, you can:

  • Quickly identify and fix issues
  • Ensure code quality through code coverage analysis
  • Share test results effectively with your team
  • Track testing progress over time

Whether you're using Jest, Mocha, or another testing framework, investing time in setting up good reporting will make your testing process more effective and efficient.

Additional Resources

Exercises

  1. Set up Jest with HTML reporting for an existing Express project.
  2. Create a custom reporter that sends test results via email or to a messaging platform like Slack.
  3. Implement a GitHub Action workflow that runs tests and publishes the results as a comment on pull requests.
  4. Create a dashboard that displays test coverage trends over time using data from your test reports.


If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)