Which scenario best fits writing a unit test in an Express application?
Unit tests focus on small parts of code working alone.
Unit tests check small pieces like functions or middleware alone, without external dependencies like databases or servers.
Which situation is best suited for an integration test in an Express app?
Integration tests check multiple parts working together.
Integration tests verify that components like route handlers and databases work together correctly.
Consider this unit test for an Express middleware that adds a header. What will the test output be?
const req = {};
const res = { setHeader: jest.fn() };
const next = jest.fn();
function addCustomHeader(req, res, next) {
res.setHeader('X-Custom', '123');
next();
}
addCustomHeader(req, res, next);
console.log(res.setHeader.mock.calls.length);Think about the environment where this code runs and what jest.fn() means.
jest.fn() is a Jest testing function. Without Jest environment, it causes ReferenceError.
Given this Express route and test, what will be the value of userCount after the test?
let userCount = 0; const express = require('express'); const app = express(); app.use(express.json()); app.post('/users', (req, res) => { userCount += 1; res.status(201).send({ id: userCount }); }); // Simulate test const request = require('supertest'); (async () => { await request(app).post('/users').send({ name: 'Alice' }); await request(app).post('/users').send({ name: 'Bob' }); console.log(userCount); })();
Each POST request increments userCount.
Two POST requests run, each increments userCount by 1, so final value is 2.
Look at this Express integration test code. Why does the test timeout instead of passing?
const express = require('express'); const app = express(); app.get('/ping', (req, res) => { setTimeout(() => res.send('pong'), 1000); }); const request = require('supertest'); test('GET /ping returns pong', async () => { const response = await request(app).get('/ping'); expect(response.text).toBe('pong'); });
Consider how long the route delays response and Jest's default timeout.
The route delays response by 1 second. Jest default timeout is 5 seconds, so normally it should pass. But if Jest timeout is set lower, test fails. The most common cause is a timeout shorter than 1000ms.