Test Cases for Registration & Login

February 14, 2024

Master the art of testing user registration and login flows with this comprehensive guide. Learn how to implement robust test cases using Mail7's testing infrastructure to ensure secure and reliable authentication systems.

Test Scenarios Overview

1. Registration Test Cases

Valid Registration

  • Valid email format
  • Password meets requirements
  • Required fields filled
  • Email verification sent
  • Account created successfully

Invalid Registration

  • Invalid email format
  • Weak password
  • Missing required fields
  • Duplicate email
  • Invalid verification token

Edge Cases

  • Special characters in fields
  • Maximum length inputs
  • Network interruptions
  • Concurrent registrations
  • Rate limiting

2. Login Test Cases

Valid Login

  • Correct credentials
  • Remember me functionality
  • Session management
  • Multi-device login
  • OAuth integration

Invalid Login

  • Incorrect password
  • Unverified email
  • Locked account
  • Expired session
  • Invalid token

Security Cases

  • Brute force protection
  • SQL injection
  • XSS prevention
  • CSRF protection
  • Password encryption

Implementation Examples

1. Registration Test Suite


// registration.test.js
const Mail7 = require('@mail7/sdk');
const { UserService } = require('./services');

describe('User Registration', () => {
    let mail7;
    let userService;
    let testEmail;

    beforeEach(async () => {
        mail7 = new Mail7({
            apiKey: process.env.MAIL7_API_KEY,
            domain: process.env.MAIL7_DOMAIN
        });
        userService = new UserService();
        testEmail = await mail7.generateEmail();
    });

    afterEach(async () => {
        await userService.cleanup();
    });

    describe('Valid Registration', () => {
        it('should register user with valid credentials', async () => {
            const response = await userService.register({
                email: testEmail,
                password: 'StrongPass123!',
                name: 'Test User'
            });

            expect(response.success).toBe(true);
            expect(response.userId).toBeDefined();

            // Verify welcome email
            const email = await mail7.waitForEmail({
                to: testEmail,
                subject: 'Welcome to Our App',
                timeout: 5000
            });

            expect(email).toBeDefined();
            expect(email.html).toContain('verify your email');
        });

        it('should handle email verification', async () => {
            await userService.register({
                email: testEmail,
                password: 'StrongPass123!',
                name: 'Test User'
            });

            // Get verification email
            const email = await mail7.waitForEmail({
                to: testEmail,
                subject: 'Verify Your Email'
            });

            // Extract verification token
            const token = extractVerificationToken(email.html);
            
            // Verify email
            const verifyResponse = await userService.verifyEmail(token);
            expect(verifyResponse.success).toBe(true);
        });
    });

    describe('Invalid Registration', () => {
        it('should reject weak passwords', async () => {
            await expect(userService.register({
                email: testEmail,
                password: 'weak',
                name: 'Test User'
            })).rejects.toThrow('Password does not meet requirements');
        });

        it('should prevent duplicate registration', async () => {
            // First registration
            await userService.register({
                email: testEmail,
                password: 'StrongPass123!',
                name: 'Test User'
            });

            // Attempt duplicate registration
            await expect(userService.register({
                email: testEmail,
                password: 'DifferentPass123!',
                name: 'Another User'
            })).rejects.toThrow('Email already registered');
        });
    });
});

2. Login Test Suite


// login.test.js
describe('User Login', () => {
    let mail7;
    let userService;
    let testEmail;
    let userId;

    beforeAll(async () => {
        mail7 = new Mail7(config);
        userService = new UserService();
        testEmail = await mail7.generateEmail();

        // Create and verify test user
        const registration = await userService.register({
            email: testEmail,
            password: 'StrongPass123!',
            name: 'Test User'
        });
        userId = registration.userId;

        const email = await mail7.waitForEmail({
            to: testEmail,
            subject: 'Verify Your Email'
        });
        await userService.verifyEmail(
            extractVerificationToken(email.html)
        );
    });

    describe('Valid Login', () => {
        it('should login with correct credentials', async () => {
            const session = await userService.login({
                email: testEmail,
                password: 'StrongPass123!'
            });

            expect(session.token).toBeDefined();
            expect(session.userId).toBe(userId);
        });

        it('should handle remember me', async () => {
            const session = await userService.login({
                email: testEmail,
                password: 'StrongPass123!',
                rememberMe: true
            });

            expect(session.token).toBeDefined();
            expect(session.expiresIn).toBeGreaterThan(7 * 24 * 60 * 60); // 7 days
        });
    });

    describe('Invalid Login', () => {
        it('should reject incorrect password', async () => {
            await expect(userService.login({
                email: testEmail,
                password: 'WrongPass123!'
            })).rejects.toThrow('Invalid credentials');
        });

        it('should lock account after multiple failures', async () => {
            const attempts = 5;
            for (let i = 0; i < attempts; i++) {
                try {
                    await userService.login({
                        email: testEmail,
                        password: 'WrongPass123!'
                    });
                } catch (error) {
                    // Expected failure
                }
            }

            await expect(userService.login({
                email: testEmail,
                password: 'StrongPass123!' // Correct password
            })).rejects.toThrow('Account locked');
        });
    });
});

3. Security Test Suite


// security.test.js
describe('Authentication Security', () => {
    describe('Rate Limiting', () => {
        it('should limit registration attempts', async () => {
            const attempts = [];
            for (let i = 0; i < 10; i++) {
                attempts.push(userService.register({
                    email: await mail7.generateEmail(),
                    password: 'StrongPass123!',
                    name: `Test User ${i}`
                }));
            }

            await expect(Promise.all(attempts))
                .rejects.toThrow('Rate limit exceeded');
        });
    });

    describe('Password Security', () => {
        it('should properly hash passwords', async () => {
            const registration = await userService.register({
                email: testEmail,
                password: 'StrongPass123!',
                name: 'Test User'
            });

            const user = await userService.findById(registration.userId);
            expect(user.password).not.toBe('StrongPass123!');
            expect(user.password).toMatch(/^\$2[ayb]\$.{56}$/); // bcrypt format
        });
    });

    describe('Session Management', () => {
        it('should invalidate old sessions on password change', async () => {
            // Login and get session
            const session = await userService.login({
                email: testEmail,
                password: 'StrongPass123!'
            });

            // Change password
            await userService.changePassword({
                userId,
                oldPassword: 'StrongPass123!',
                newPassword: 'NewStrongPass123!'
            });

            // Try to use old session
            await expect(userService.validateSession(session.token))
                .rejects.toThrow('Invalid session');
        });
    });
});

Best Practices

1. Test Data Management

  • Use unique test emails for each test
  • Clean up test data after each test run
  • Implement proper test isolation
  • Use meaningful test data patterns

2. Security Testing

  • Test password complexity requirements
  • Verify rate limiting implementation
  • Check session management
  • Test account lockout policies

3. Error Handling

  • Test all validation error cases
  • Verify error messages are user-friendly
  • Check error response formats
  • Test error recovery flows

4. Performance

  • Test registration throughput
  • Measure login response times
  • Verify concurrent user handling
  • Test under different load conditions

Common Pitfalls

Registration Issues

  • Weak password validation
  • Missing email verification
  • Insufficient rate limiting
  • Poor error handling

Login Problems

  • Insecure session management
  • Missing brute force protection
  • Poor password storage
  • Weak account recovery

Security Vulnerabilities

  • SQL injection risks
  • XSS vulnerabilities
  • CSRF weaknesses
  • Insufficient logging

Start Testing Now

Ready to implement comprehensive registration and login testing in your application? Get started with our powerful testing toolkit: