API Testing Development (Supertest)
Supertest is a Node.js library for testing HTTP endpoints directly through an Express/Fastify/NestJS application without running a server. Ideal for integration testing REST APIs in JavaScript projects.
Installation
npm install -D supertest @types/supertest
Basic Tests (Express)
// tests/api/auth.test.ts
import request from 'supertest';
import { app } from '../../src/app';
import { db } from '../../src/database';
beforeAll(async () => await db.migrate.latest());
afterAll(async () => await db.destroy());
afterEach(async () => await db('users').truncate());
describe('POST /api/auth/login', () => {
beforeEach(async () => {
await request(app).post('/api/users').send({
email: '[email protected]',
password: 'password123',
name: 'Test User',
});
});
it('returns 200 and token on valid credentials', async () => {
const res = await request(app)
.post('/api/auth/login')
.send({ email: '[email protected]', password: 'password123' })
.expect(200)
.expect('Content-Type', /json/);
expect(res.body).toMatchObject({
access_token: expect.any(String),
user: {
email: '[email protected]',
name: 'Test User',
},
});
expect(res.body.access_token).toHaveLength(171); // JWT length
});
it('returns 401 on wrong password', async () => {
const res = await request(app)
.post('/api/auth/login')
.send({ email: '[email protected]', password: 'wrongpass' })
.expect(401);
expect(res.body.message).toBe('Invalid credentials');
});
it('returns 422 on missing fields', async () => {
const res = await request(app)
.post('/api/auth/login')
.send({ email: '[email protected]' }) // no password
.expect(422);
expect(res.body.errors).toHaveProperty('password');
});
});
Authorized Requests
// tests/helpers/auth.ts
export async function getAuthToken(
app: Express,
email = '[email protected]',
password = 'adminpass'
): Promise<string> {
const res = await request(app)
.post('/api/auth/login')
.send({ email, password });
return res.body.access_token;
}
// tests/api/products.test.ts
describe('Products API', () => {
let token: string;
beforeAll(async () => {
token = await getAuthToken(app);
});
it('creates product with auth', async () => {
const res = await request(app)
.post('/api/products')
.set('Authorization', `Bearer ${token}`)
.send({ name: 'MacBook Pro', price: 150000, slug: 'macbook-pro' })
.expect(201);
expect(res.body.id).toBeDefined();
expect(res.body.slug).toBe('macbook-pro');
});
it('returns 403 without auth', async () => {
await request(app)
.post('/api/products')
.send({ name: 'MacBook' })
.expect(401);
});
});
Testing File Uploads
it('uploads product image', async () => {
const res = await request(app)
.post('/api/products/1/images')
.set('Authorization', `Bearer ${token}`)
.attach('image', Buffer.from('fake-image-data'), {
filename: 'product.jpg',
contentType: 'image/jpeg',
})
.expect(200);
expect(res.body.url).toMatch(/^https:\/\/.+\.jpg$/);
});
Testing Pagination and Filtering
describe('GET /api/products', () => {
beforeEach(async () => {
await db('products').insert([
{ name: 'Product 1', price: 1000, category: 'electronics' },
{ name: 'Product 2', price: 2000, category: 'electronics' },
{ name: 'Product 3', price: 3000, category: 'clothing' },
]);
});
it('paginates results', async () => {
const res = await request(app)
.get('/api/products?page=1&limit=2')
.expect(200);
expect(res.body.data).toHaveLength(2);
expect(res.body.meta.total).toBe(3);
expect(res.body.meta.last_page).toBe(2);
});
it('filters by category', async () => {
const res = await request(app)
.get('/api/products?category=electronics')
.expect(200);
expect(res.body.data).toHaveLength(2);
res.body.data.forEach(p => expect(p.category).toBe('electronics'));
});
});
NestJS Integration
import { Test } from '@nestjs/testing';
import * as request from 'supertest';
describe('UsersController', () => {
let app: INestApplication;
beforeAll(async () => {
const moduleRef = await Test.createTestingModule({
imports: [AppModule],
}).compile();
app = moduleRef.createNestApplication();
await app.init();
});
afterAll(async () => await app.close());
it('GET /users', () => {
return request(app.getHttpServer())
.get('/users')
.expect(200)
.expect(res => expect(Array.isArray(res.body)).toBeTruthy());
});
});
Implementation Timeline
Writing integration API tests for 15–25 endpoints: 3–5 days.







