0
0
Expressframework~5 mins

Jest or Vitest setup for Express

Choose your learning style9 modes available
Introduction

We use Jest or Vitest to check if our Express app works correctly. They help us find mistakes early by running tests automatically.

When you want to make sure your Express routes return the right responses.
When you add new features and want to confirm old parts still work.
When you fix bugs and want to check the fix works without breaking anything else.
When you want to run tests automatically before sharing your code.
When you want to practice writing small checks for your app's behavior.
Syntax
Express
npm install --save-dev jest supertest

// or for Vitest:
npm install --save-dev vitest supertest

Jest and Vitest are testing tools that run your tests and show results.

Supertest helps to test Express routes by simulating HTTP requests.

Examples
This example uses Jest to test that the home route returns status 200.
Express
import request from 'supertest';
import app from './app';

test('GET / returns 200', async () => {
  const response = await request(app).get('/');
  expect(response.status).toBe(200);
});
This example uses Vitest with similar test structure for the same route.
Express
import { describe, it, expect } from 'vitest';
import request from 'supertest';
import app from './app';

describe('GET /', () => {
  it('should return 200 OK', async () => {
    const res = await request(app).get('/');
    expect(res.status).toBe(200);
  });
});
Sample Program

This is a simple Express app with one route. The test checks if the route returns status 200 and the text 'Hello World'.

Express
// app.js
import express from 'express';
const app = express();

app.get('/', (req, res) => {
  res.status(200).send('Hello World');
});

export default app;

// app.test.js (for Jest)
import request from 'supertest';
import app from './app';

test('GET / returns Hello World', async () => {
  const response = await request(app).get('/');
  expect(response.status).toBe(200);
  expect(response.text).toBe('Hello World');
});
OutputSuccess
Important Notes

Always export your Express app without listening to a port for easier testing.

Use Supertest to simulate HTTP requests without starting the server.

Run tests with npm test after setting up scripts in package.json.

Summary

Jest and Vitest help test Express apps by running code that simulates requests.

Supertest works with both to make HTTP calls inside tests.

Keep your app export separate from server start for easier testing.