Why Test APIs?
Testing ensures your API works correctly, handles errors properly, and maintains quality as you add new features.
Writing API Tests
const request = require('supertest');
const app = require('../server');
describe('User API', () => {
test('GET /api/users - should return all users', async () => {
const response = await request(app)
.get('/api/users')
.expect(200);
expect(Array.isArray(response.body)).toBe(true);
});
test('POST /api/users - should create a new user', async () => {
const response = await request(app)
.post('/api/users')
.send({ name: 'Test', email: 'test@example.com' })
.expect(201);
expect(response.body.name).toBe('Test');
});
});
Best Practices
- Test all endpoints
- Test success and error cases
- Test edge cases
- Use test databases
- Clean up test data