Performance: Supertest for HTTP assertions
This affects the speed and reliability of backend API testing, impacting development feedback loops but not the frontend rendering performance.
import request from 'supertest'; import app from './app'; describe('GET /users', () => { it('responds with json', async () => { await request(app) .get('/users') .expect('Content-Type', /json/) .expect(200); }); });
const request = require('supertest'); const app = require('./app'); describe('GET /users', () => { it('responds with json', (done) => { request(app) .get('/users') .expect('Content-Type', /json/) .expect(200) .end((err, res) => { if (err) return done(err); done(); }); }); });
| Pattern | Test Execution Time | Server Lifecycle | Error Handling | Verdict |
|---|---|---|---|---|
| Callback style with .end() | Slower due to callbacks | Starts/stops server per test (if misused) | Harder to catch errors quickly | [X] Bad |
| Async/await style | Faster with async code | Single server lifecycle | Better error propagation | [OK] Good |
Supertest in Express applications?const request = require('supertest');.import request from 'supertest';
import express from 'express';
const app = express();
app.get('/hello', (req, res) => res.status(200).send('Hi'));
test('GET /hello returns status 200', async () => {
const response = await request(app).get('/hello');
expect(response.status).toBe(201);
});/hello sends a response with status code 200 and body 'Hi'.import request from 'supertest';
import app from './app';
test('POST /data returns 201', async () => {
const res = await request(app).post('/data')
.send({ name: 'Alice' })
.expect(201);
expect(res.body.name).toBe('Alice');
});await is correctly used before request(app).post(...), so the promise resolves before assertions..expect(201) is valid and chaining expect(res.body.name).toBe('Alice') is correct after awaiting the response.type=admin is present, otherwise it returns 403 Forbidden. Which Supertest code snippet correctly tests the 403 response when the query parameter is missing?type=admin is present; otherwise, it returns 403 Forbidden.type=user, which is not missing but wrong type, so may or may not return 403 depending on implementation. await request(app).post('/secret').send({ type: 'admin' }).expect(403); uses POST instead of GET. await request(app).get('/secret?type=admin').expect(403); sends type=admin which should return success, not 403.Pass the test and this pattern moves unknown