Files
fast-next-template/frontend/e2e/auth-guard.spec.ts
Felipe Cardoso a95b25cab8 Enhance Playwright test coverage and refactor e2e authentication tests
- Improved validation checks with element ID and class-specific locators for better accuracy and resilience.
- Removed outdated form behaviors (e.g., "Remember me" and test-only shortcuts) for updated flows.
- Refactored test cases to reflect backend changes, and standardized password validation and error messages.
- Updated selector usage to leverage `getByRole` for improved accessibility testing.
- Reorganized and optimized test timeouts and interactivity delays for faster execution.
2025-11-01 13:12:15 +01:00

202 lines
5.9 KiB
TypeScript

import { test, expect } from '@playwright/test';
test.describe('AuthGuard - Route Protection', () => {
test.beforeEach(async ({ page, context }) => {
// Clear storage before each test to ensure clean state
await context.clearCookies();
await page.goto('/');
await page.evaluate(() => {
localStorage.clear();
sessionStorage.clear();
});
});
test('should redirect to login when accessing protected route without auth', async ({
page,
}) => {
// Try to access a protected route (if you have one)
// For now, we'll test the root if it's protected
// Adjust the route based on your actual protected routes
await page.goto('/');
// If root is protected, should redirect to login or show homepage
// Wait for page to stabilize
await page.waitForTimeout(1000);
// Should either be on login or homepage (not crashing)
const url = page.url();
expect(url).toMatch(/\/(login)?$/);
});
test('should allow access to public routes without auth', async ({ page }) => {
// Test login page
await page.goto('/login');
await expect(page).toHaveURL('/login');
await expect(page.locator('h2')).toContainText('Sign in to your account');
// Test register page
await page.goto('/register');
await expect(page).toHaveURL('/register');
await expect(page.locator('h2')).toContainText('Create your account');
// Test password reset page
await page.goto('/password-reset');
await expect(page).toHaveURL('/password-reset');
await expect(page.locator('h2')).toContainText('Reset your password');
});
test('should persist authentication across page reloads', async ({ page }) => {
// Manually set a mock token in localStorage for testing
await page.goto('/');
await page.evaluate(() => {
const mockToken = {
access_token: 'mock-access-token',
refresh_token: 'mock-refresh-token',
user: {
id: 1,
email: 'test@example.com',
first_name: 'Test',
last_name: 'User',
is_active: true,
},
};
localStorage.setItem('auth_token', JSON.stringify(mockToken));
});
// Reload the page
await page.reload();
// Should still have the token
const hasToken = await page.evaluate(() => {
return localStorage.getItem('auth_token') !== null;
});
expect(hasToken).toBe(true);
});
test('should clear authentication on logout', async ({ page }) => {
// Set up authenticated state
await page.goto('/');
await page.evaluate(() => {
const mockToken = {
access_token: 'mock-access-token',
refresh_token: 'mock-refresh-token',
user: {
id: 1,
email: 'test@example.com',
first_name: 'Test',
last_name: 'User',
is_active: true,
},
};
localStorage.setItem('auth_token', JSON.stringify(mockToken));
});
// Reload to apply token
await page.reload();
// Simulate logout by clearing storage
await page.evaluate(() => {
localStorage.clear();
sessionStorage.clear();
});
// Reload page
await page.reload();
// Storage should be clear
const hasToken = await page.evaluate(() => {
return localStorage.getItem('auth_token') === null;
});
expect(hasToken).toBe(true);
});
test('should not allow access to auth pages when already logged in', async ({ page }) => {
// Set up authenticated state
await page.goto('/');
await page.evaluate(() => {
const mockToken = {
access_token: 'mock-access-token',
refresh_token: 'mock-refresh-token',
user: {
id: 1,
email: 'test@example.com',
first_name: 'Test',
last_name: 'User',
is_active: true,
},
};
localStorage.setItem('auth_token', JSON.stringify(mockToken));
});
// Try to access login page
await page.goto('/login');
// Wait a bit for potential redirect
await page.waitForTimeout(2000);
// Check current state - might stay on login or redirect
// Implementation-dependent
const currentUrl = page.url();
// At minimum, page should load without errors
expect(currentUrl).toBeTruthy();
});
test('should handle expired tokens gracefully', async ({ page }) => {
// Set up authenticated state with expired token
await page.goto('/');
await page.evaluate(() => {
const expiredToken = {
access_token: 'expired-access-token',
refresh_token: 'expired-refresh-token',
user: {
id: 1,
email: 'test@example.com',
first_name: 'Test',
last_name: 'User',
is_active: true,
},
};
localStorage.setItem('auth_token', JSON.stringify(expiredToken));
});
// Try to access a protected route
// Backend should return 401, triggering logout
await page.reload();
// Wait for potential redirect to login
await page.waitForTimeout(3000);
// Should eventually be redirected or have token cleared
// This depends on token refresh logic
});
test('should preserve intended destination after login', async ({ page }) => {
// This is a nice-to-have feature that requires protected routes
// For now, just verify the test doesn't crash
await page.goto('/');
// Login (via localStorage for testing)
await page.evaluate(() => {
const mockToken = {
access_token: 'mock-access-token',
refresh_token: 'mock-refresh-token',
user: {
id: 1,
email: 'test@example.com',
first_name: 'Test',
last_name: 'User',
is_active: true,
},
};
localStorage.setItem('auth_token', JSON.stringify(mockToken));
});
// Reload page
await page.reload();
await page.waitForTimeout(1000);
// Verify page loaded successfully
expect(page.url()).toBeTruthy();
});
});