Performance: Testing GET endpoints
Testing GET endpoints affects development speed and reliability but can indirectly impact user experience by ensuring fast and correct responses.
import request from 'supertest'; import app from './app'; describe('GET /items', () => { it('responds with JSON', async () => { const res = await request(app).get('/items'); expect(res.statusCode).toBe(200); expect(res.body).toBeDefined(); }); });
const request = require('supertest'); const app = require('./app'); describe('GET /items', () => { it('responds with JSON', (done) => { request(app) .get('/items') .end((err, res) => { if (err) return done(err); expect(res.statusCode).toBe(200); expect(res.body).toBeDefined(); done(); }); }); });
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Callback style test with .end() | 0 | 0 | 0 | [X] Bad |
| Async/await style test | 0 | 0 | 0 | [OK] Good |
const express = require('express');
const app = express();
app.get('/hello', (req, res) => res.json({ message: 'Hi!' }));
const request = require('supertest');
test('GET /hello returns message', async () => {
const response = await request(app).get('/hello');
return response.body.message;
});const request = require('supertest');
const app = require('./app');
test('GET /users returns 200', () => {
request(app)
.get('/users')
.expect(200);
});app.get('/active-users', (req, res) => {
const users = [
{ id: 1, active: true },
{ id: 2, active: false },
{ id: 3, active: true }
];
res.json(users.filter(u => u.active));
});
// Test code options:
A) await request(app).get('/active-users').expect(200).expect(res => {
if (!res.body.every(u => u.active)) throw new Error('Inactive user found');
});
B) await request(app).get('/active-users').expect(200).expect(res => {
if (res.body.length !== 3) throw new Error('Wrong number of users');
});
C) await request(app).get('/active-users').expect(404);
D) await request(app).get('/active-users').expect(200).expect(res => {
if (!res.body.some(u => u.active === false)) throw new Error('Inactive user found');
});Pass the test and this pattern moves unknown