Performance: Testing API routes
Testing API routes affects development speed and reliability but can indirectly impact user experience by preventing slow or broken API responses.
import request from 'supertest'; import app from '../../pages/api/hello'; describe('API route /api/hello', () => { it('responds with 200 and JSON', async () => { const response = await request(app).get('/api/hello'); expect(response.status).toBe(200); expect(response.body).toHaveProperty('message'); }); });
import handler from '../../pages/api/hello'; test('API returns 200', async () => { const req = {}; const res = { status: jest.fn().mockReturnThis(), json: jest.fn() }; await handler(req, res); expect(res.status).toHaveBeenCalledWith(200); });
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Manual mocks for API testing | 0 (no DOM) | 0 | 0 | [X] Bad |
| HTTP simulation with supertest | 0 (no DOM) | 0 | 0 | [OK] Good |
import handler from 'path' to import default export correctly.res.status(200).json({ message: 'OK' })?
import handler from '../pages/api/hello';
import { createMocks } from 'node-mocks-http';
test('returns 200 status', async () => {
const { req, res } = createMocks({ method: 'GET' });
await handler(req, res);
expect(res._getStatusCode()).toBe(200);
});import handler from '../pages/api/hello';
import { createMocks } from 'node-mocks-http';
test('returns 200 status', () => {
const { req, res } = createMocks({ method: 'GET' });
handler(req, res);
expect(res._getStatusCode()).toBe(200);
});Pass the test and this pattern moves unknown