Files
PicAnalysis/frontend/e2e/auth.spec.ts

99 lines
2.9 KiB
TypeScript
Raw Normal View History

import { test, expect } from '@playwright/test';
test.describe('Authentication', () => {
test.beforeEach(async ({ page }) => {
await page.goto('/');
});
test('应该显示登录页面', async ({ page }) => {
await expect(page.locator('h1')).toContainText('图片分析系统');
await expect(page.locator('text=登录以继续')).toBeVisible();
});
test('应该验证登录表单', async ({ page }) => {
// 测试空表单
await page.click('button[type="submit"]');
await expect(page.locator('text=请输入用户名和密码')).toBeVisible();
// 测试只有用户名
await page.fill('input[label="用户名"]', 'testuser');
await page.click('button[type="submit"]');
await expect(page.locator('text=请输入用户名和密码')).toBeVisible();
});
test('应该成功登录并跳转到仪表盘', async ({ page }) => {
// Mock 登录 API
await page.route('**/api/auth/login', (route) => {
route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({
success: true,
data: {
token: 'test-token',
user: {
id: '1',
username: 'testuser',
email: 'test@example.com',
created_at: '2024-01-01',
updated_at: '2024-01-01',
},
},
}),
});
});
await page.fill('input[label="用户名"]', 'testuser');
await page.fill('input[label="密码"]', 'password123');
await page.click('button[type="submit"]');
// 验证跳转到仪表盘
await expect(page).toHaveURL('/dashboard');
await expect(page.locator('h2')).toContainText('仪表盘');
});
test('应该显示登录错误', async ({ page }) => {
await page.route('**/api/auth/login', (route) => {
route.fulfill({
status: 401,
contentType: 'application/json',
body: JSON.stringify({
success: false,
error: '用户名或密码错误',
}),
});
});
await page.fill('input[label="用户名"]', 'wronguser');
await page.fill('input[label="密码"]', 'wrongpass');
await page.click('button[type="submit"]');
await expect(page.locator('text=用户名或密码错误')).toBeVisible();
});
test('应该能够退出登录', async ({ page }) => {
// 设置已登录状态
await page.goto('/');
await page.evaluate(() => {
localStorage.setItem('auth-storage', JSON.stringify({
state: {
user: { id: '1', username: 'test' },
token: 'test-token',
isAuthenticated: true,
},
version: 0,
}));
localStorage.setItem('auth_token', 'test-token');
});
await page.goto('/dashboard');
// 点击退出登录
await page.click('text=退出登录');
// 验证返回登录页
await expect(page).toHaveURL('/login');
await expect(page.locator('h1')).toContainText('图片分析系统');
});
});