13. Testing APIs: Integration Tests for Backend Endpoints
API testing is essential for backend services. It ensures your endpoints work correctly, handle errors gracefully, and meet performance requirements. This module covers testing REST APIs, GraphQL, and gRPC endpoints.
The key insight is that API tests should cover the entire request-response cycle. They should test: request validation, business logic, database operations, error handling, and response formats. Understanding API testing is essential for backend development.
This module covers testing tools, writing API tests, and best practices.
Testing REST APIs
REST API testing involves sending HTTP requests and verifying responses. Tools like Supertest, Postman, and Jest can be used. Tests should cover: success cases, error cases, authentication, authorization, and edge cases.
API tests should be fast and independent. Use a test database or mock external dependencies. Run tests in isolation to avoid conflicts. Understanding API testing is essential for backend reliability.
Try It Yourself: API Testing
Follow these steps to practice API testing.
Step 1: Set up the server// server.js<br>import express from <strong><code>express;
const app = express();
app.use(express.json());
let users = [];
let id = 1;
app.get(/users, (req, res) => {
res.json(users);
});
app.get(/users/:id, (req, res) => {
const user = users.find(u => u.id === Number(req.params.id));
if (!user) return res.status(404).json({ error: User not found });
res.json(user);
});
app.post(/users, (req, res) => {
const { name, email } = req.body;
if (!name || !email) {
return res.status(400).json({ error: Name and email required });
}
const user = { id: id++, name, email };
users.push(user);
res.status(201).json(user);
});
export default app;
Step 2: Write API tests// server.test.js<br>import request from <strong><code>supertest;
import app from ./server;
describe(API Tests, () => {
beforeEach(() => {
// Reset state
users = [];
id = 1;
});
test(GET /users returns empty array initially, async () => {
const res = await request(app).get(/users);
expect(res.status).toBe(200);
expect(res.body).toEqual([]);
});
test(POST /users creates a new user, async () => {
const res = await request(app)
.post(/users)
.send({ name: Alice, email: alice@example.com });
expect(res.status).toBe(201);
expect(res.body).toHaveProperty(id, 1);
expect(res.body.name).toBe(Alice);
expect(res.body.email).toBe(alice@example.com);
});
test('POST /users returns 400 for missing fields', async () => {
const res = await request(app)
.post(/users)
.send({ name: Alice });
expect(res.status).toBe(400);
expect(res.body.error).toBe(Name and email required);
});
test(GET /users/:id returns user by id, async () => {
await request(app).post(/users).send({ name: Bob, email: bob@example.com });
const res = await request(app).get(/users/1);
expect(res.status).toBe(200);
expect(res.body).toHaveProperty(id, 1);
expect(res.body.name).toBe(Bob);
});
test('GET /users/:id returns 404 for non-existent user', async () => {
const res = await request(app).get(/users/999);
expect(res.status).toBe(404);
expect(res.body.error).toBe(User not found);
});
});
Step 3: Run the testsnpm test
Try It Yourself: Add PUT and DELETE endpoints. Write tests for them.
Knowledge Check
Ready to test your understanding of 13. Testing APIs: Integration Tests for Backend Endpoints?