📋 MCP:实现网页自动化测试

🎯 概述

在现代化的 Web 开发中,自动化测试已成为确保应用质量、加速迭代周期的关键环节。Playwright 凭借其跨浏览器支持、强大的自动化能力以及灵活的 API,成为自动化端到端测试的理想选择。本最佳实践将详细介绍如何在 Trae IDE 中高效集成 Playwright 这一 MCP Server,构建自动化测试解决方案,帮助你快速验证网页的交互逻辑,减少人工测试成本,提升整体开发效率。

🚀 效果展示

以下为部分使用 Trae IDE 自动化测试网页的效果展示:

  • 跨浏览器测试: 同时在 Chrome、Firefox、Safari 等浏览器中执行测试
  • 视觉对比测试: 自动对比页面截图,检测视觉差异
  • 端到端流程测试: 模拟用户完整操作流程,验证业务逻辑
  • 性能监控: 记录页面加载时间、资源使用情况等性能指标

🛠️ 演示环境

本教程使用的系统环境如下:

  • Trae IDE 版本: 0.5.5
  • 操作系统: macOS 14.7
  • Node.js 版本: 20.19.1
  • npm 版本: 10.9.2
  • Playwright 版本: 1.47.0

🔧 准备工作

1. 安装 Playwright

在项目目录中执行以下命令安装 Playwright:

npm init -y
npm install -D @playwright/test
npx playwright install

2. 配置 Playwright

创建 playwright.config.ts 文件,配置测试环境:

// playwright.config.ts
import { defineConfig, devices } from '@playwright/test';

export default defineConfig({
  testDir: './tests',
  timeout: 30 * 1000,
  expect: {
    timeout: 5000
  },
  fullyParallel: true,
  retries: 2,
  reporter: [
    ['html'],
    ['json', { outputFile: 'test-results/results.json' }]
  ],
  use: {
    actionTimeout: 0,
    baseURL: 'http://localhost:3000',
    screenshot: 'only-on-failure',
    video: 'retain-on-failure',
  },
  projects: [
    {
      name: 'chromium',
      use: { ...devices['Desktop Chrome'] },
    },
    {
      name: 'firefox',
      use: { ...devices['Desktop Firefox'] },
    },
    {
      name: 'webkit',
      use: { ...devices['Desktop Safari'] },
    },
  ],
  webServer: {
    command: 'npm run dev',
    port: 3000,
    reuseExistingServer: !process.env.CI,
  },
});

📝 实现步骤

步骤 1:创建测试目录结构

mkdir -p tests
mkdir -p tests/pages
mkdir -p tests/utils
mkdir -p tests/fixtures

步骤 2:创建页面对象模型

创建 tests/pages/login.page.ts 文件,实现登录页面的页面对象:

// tests/pages/login.page.ts
import { Page, Locator } from '@playwright/test';

export class LoginPage {
  readonly page: Page;
  readonly usernameInput: Locator;
  readonly passwordInput: Locator;
  readonly loginButton: Locator;
  readonly errorMessage: Locator;

  constructor(page: Page) {
    this.page = page;
    this.usernameInput = page.locator('input[name="username"]');
    this.passwordInput = page.locator('input[name="password"]');
    this.loginButton = page.locator('button[type="submit"]');
    this.errorMessage = page.locator('.error-message');
  }

  async goto() {
    await this.page.goto('/login');
  }

  async login(username: string, password: string) {
    await this.usernameInput.fill(username);
    await this.passwordInput.fill(password);
    await this.loginButton.click();
  }

  async getErrorMessage() {
    return await this.errorMessage.textContent();
  }
}

步骤 3:实现测试用例

创建 tests/login.spec.ts 文件,编写登录功能的测试用例:

// tests/login.spec.ts
import { test, expect } from '@playwright/test';
import { LoginPage } from './pages/login.page';

test.describe('登录功能测试', () => {
  let loginPage: LoginPage;

  test.beforeEach(async ({ page }) => {
    loginPage = new LoginPage(page);
    await loginPage.goto();
  });

  test('成功登录', async ({ page }) => {
    await loginPage.login('admin', 'password123');
    await expect(page).toHaveURL('/dashboard');
    await expect(page.locator('.welcome-message')).toContainText('欢迎,admin');
  });

  test('用户名为空', async () => {
    await loginPage.login('', 'password123');
    await expect(loginPage.errorMessage).toContainText('用户名不能为空');
  });

  test('密码错误', async () => {
    await loginPage.login('admin', 'wrongpassword');
    await expect(loginPage.errorMessage).toContainText('用户名或密码错误');
  });
});

步骤 4:创建自定义工具函数

创建 tests/utils/helper.ts 文件,提供测试辅助功能:

// tests/utils/helper.ts
import { Page } from '@playwright/test';

export async function takeScreenshot(page: Page, name: string) {
  await page.screenshot({ path: `test-results/screenshots/${name}.png` });
}

export async function waitForNetworkIdle(page: Page, timeout = 30000) {
  await page.waitForLoadState('networkidle', { timeout });
}

export function generateRandomEmail() {
  return `test${Math.floor(Math.random() * 10000)}@example.com`;
}

步骤 5:运行测试

执行以下命令运行测试:

npx playwright test

查看测试报告:

npx playwright show-report

📊 功能特性

核心功能

  • 跨浏览器测试: 支持 Chrome、Firefox、Safari 等主流浏览器
  • 端到端测试: 模拟用户完整操作流程,验证业务逻辑
  • 页面对象模型: 采用 POM 模式,提高测试代码的可维护性
  • 自动等待: 智能等待元素加载,减少测试不稳定因素
  • 网络请求拦截: 可以模拟和修改网络请求,测试各种场景
  • 视觉对比: 自动对比页面截图,检测视觉回归问题

技术特点

  • TypeScript 支持: 提供类型安全,减少运行时错误
  • 并行执行: 支持并行运行测试,提高测试效率
  • 重试机制: 自动重试失败的测试,提高测试稳定性
  • 丰富的断言 API: 提供多种断言方法,方便验证测试结果
  • 详细的测试报告: 生成直观的测试报告,便于分析测试结果

🚩 使用示例

基本测试示例

// tests/example.spec.ts
import { test, expect } from '@playwright/test';

test('基本页面测试', async ({ page }) => {
  await page.goto('https://example.com');
  await expect(page).toHaveTitle('Example Domain');
  await expect(page.locator('h1')).toContainText('Example Domain');
});

复杂交互测试

// tests/complex-interaction.spec.ts
import { test, expect } from '@playwright/test';

test('复杂交互测试', async ({ page }) => {
  await page.goto('https://example.com');
  
  // 点击链接
  await page.click('a');
  
  // 填写表单
  await page.fill('input[name="username"]', 'testuser');
  await page.fill('input[name="password"]', 'password');
  
  // 提交表单
  await page.click('button[type="submit"]');
  
  // 验证结果
  await expect(page).toHaveURL('https://example.com/dashboard');
  await expect(page.locator('.user-profile')).toBeVisible();
});

网络请求测试

// tests/network.spec.ts
import { test, expect } from '@playwright/test';

test('网络请求测试', async ({ page }) => {
  // 拦截网络请求
  await page.route('**/api/data', async (route) => {
    await route.fulfill({
      status: 200,
      body: JSON.stringify({ message: 'Mocked data' }),
    });
  });
  
  await page.goto('https://example.com');
  await expect(page.locator('.data-message')).toContainText('Mocked data');
});

⚠️ 注意事项

  1. 测试环境隔离: 确保测试之间相互独立,避免测试数据污染
  2. 测试稳定性: 避免使用硬编码的等待时间,尽量使用 Playwright 的自动等待机制
  3. 性能考虑: 合理设置测试超时时间,避免测试运行过久
  4. 错误处理: 完善测试代码的错误处理,提高测试的健壮性
  5. 测试数据管理: 考虑使用测试数据工厂或固定装置来管理测试数据
  6. CI/CD 集成: 确保测试能够在 CI/CD 环境中正常运行
  7. 并行测试: 合理配置并行测试数量,避免资源竞争

📚 相关资源

💡 总结

通过本教程,你已经学习了如何在 Trae IDE 中使用 Playwright MCP Server 实现网页自动化测试。Playwright 作为一个功能强大的自动化测试框架,提供了丰富的 API 和工具,可以帮助你构建稳定、高效的自动化测试套件。

采用页面对象模型、合理的测试结构和最佳实践,可以显著提高测试代码的可维护性和可扩展性。通过持续的自动化测试,可以及早发现和解决问题,确保应用的质量和稳定性。

随着项目的发展,你还可以进一步扩展测试覆盖范围,包括性能测试、安全测试等,为项目的成功保驾护航。

祝你测试顺利!🌟

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐