Test Validation and Authorization
A complete test suite should also verify invalid input and access restrictions.
Important test cases include:
- Registration with missing name.
- Registration with invalid email.
- Registration with a short password.
- Duplicate email registration.
- Login with incorrect credentials.
- Accessing protected routes without a token.
- Accessing administrator routes as a normal user.
- Updating another user's profile.
Negative test cases are particularly important because they verify that the API rejects unauthorized and invalid operations.
Test Invalid Registration
test('should reject an invalid email address', async () => {
const response = await request(app)
.post('/api/v1/auth/register')
.send({
name: 'John Doe',
email: 'invalid-email',
password: 'SecurePassword123!'
});
expect(response.status).toBe(400);
expect(response.body.success).toBe(false);
});
test('should reject an unauthenticated request', async () => {
const response = await request(app)
.get('/api/v1/users');
expect(response.status).toBe(401);
});Verifies that invalid registration data and unauthenticated requests are rejected.
Key Takeaways
Test invalid inputs as well as successful requests.
Verify that protected endpoints reject unauthenticated clients.
Test ownership and role-based restrictions.