Commit 5617f1b0 by chenwq

```

feat(e2e): 添加E2E自动化测试项目配置

- 新增项目配置文件,包括环境变量示例(.env.example)和忽略规则(.gitignore)
- 配置不同测试环境(local/dev/test)的基础URL和账号管理
- 实现测试账号认证机制和登录页面自动化登录功能
- 创建基础测试用例和SAAS-V5.8.6版本相关采购发货页面测试
- 设置Playwright测试框架配置,支持多浏览器测试(Edge/Firefox/WebKit)

docs(e2e): 完善项目文档和使用说明

- 编写详细的README.md文档,包含常用命令、用例范围、浏览器选择说明
- 文档化环境地址配置、测试账号设置和报告查看方法
- 提供本地环境IP自动识别和手动指定的使用指导

refactor(e2e): 重构测试执行脚本和面板界面

- 替换原有测试命令为新的run-e2e.mjs脚本,支持环境参数传递
- 开发E2E测试面板界面,提供可视化的项目、环境、用例范围选择
- 实现测试结果实时输出和报告展示功能
- 移除原有的example测试用例,采用新的测试组织结构
```
1 parent 7679da67
E2E_USERNAME=
E2E_PASSWORD=
......@@ -6,3 +6,5 @@ node_modules/
/blob-report/
/playwright/.cache/
/playwright/.auth/
.env.local
# E2E 自动化测试项目
这个项目用于运行 SAAS+ 的 Playwright 自动化测试,默认只测试 Edge 浏览器。
## 常用命令
| 命令 | 作用 | 什么时候用 |
| --- | --- | --- |
| `npm test` | 使用默认环境运行 Edge 测试 | 不指定环境时使用,目前默认是测试环境 |
| `npm run test:local` | 运行本地开发环境 Edge 测试 | 本地前端服务已经启动后使用 |
| `npm run test:dev` | 运行开发环境 Edge 测试 | 要测开发环境地址时使用 |
| `npm run test:test` | 运行测试环境 Edge 测试 | 要测测试环境地址时使用,日常验证优先用这个 |
| `npm run panel` | 启动可视化测试面板 | 想在浏览器里点按钮运行测试、查看报告时使用 |
## 用例范围
用例按目录区分:
| 范围 | 目录 | 说明 |
| --- | --- | --- |
| 基础功能 | `projects/dj-carlife-web/tests/basic` | 登录页、系统底层能力等通用用例 |
| SAAS-V5.8.6 | `projects/dj-carlife-web/tests/saas-v5.8.6` | 5.8.6 版本新增需求用例 |
| 全部用例 | `tests` | 基础功能 + 各版本用例 |
命令行可以这样选择范围:
```bash
npm run test:test -- --suite=basic
npm run test:test -- --suite=saas-v5.8.6
npm run test:test
```
面板里也可以通过“用例范围”选择当前运行基础功能、SAAS-V5.8.6,或全部用例。
## 浏览器选择
默认只跑 Edge。
如果要跑全部浏览器,可以在面板里选择“全部浏览器”。全部浏览器包含:
- Edge
- Firefox
- WebKit
命令行也可以手动指定:
```bash
npm run test:test -- --project=edge
npm run test:test -- --project=firefox
npm run test:test -- --project=webkit
```
如果要一次跑全部浏览器,使用:
```bash
npm run test:test -- --project=edge --project=firefox --project=webkit
```
## 环境地址
| 环境 | 地址 |
| --- | --- |
| 本地环境 local | `http://本机IP:8080/dj-carlife-web/#/` |
| 开发环境 dev | `http://192.168.3.191:8543/#/` |
| 测试环境 test | `http://frontend.test.glsx.com.cn/dj-carlife-web/#/` |
本地环境的 IP 会在每次运行时自动读取当前电脑的局域网 IP,不需要手动写死 `192.168.2.31`。
如果自动识别到的 IP 不对,可以临时指定:
```bash
E2E_LOCAL_HOST=192.168.x.x npm run test:local
```
在 Windows PowerShell 中可以这样写:
```powershell
$env:E2E_LOCAL_HOST="192.168.x.x"; npm run test:local
```
## 测试账号
测试账号和密码不要写进代码里,放在 `.env.local`:
```bash
E2E_USERNAME=账号
E2E_PASSWORD=密码
```
## 查看报告
运行测试后会生成 Playwright 报告。推荐直接启动面板:
```bash
npm run panel
```
面板会从 `5200` 端口开始启动,如果端口被占用,会自动尝试下一个端口。
......@@ -3,7 +3,11 @@
"version": "1.0.0",
"main": "index.js",
"scripts": {
"serve": "playwright test"
"panel": "node tools/e2e-panel/server.mjs",
"test": "node scripts/run-e2e.mjs",
"test:local": "node scripts/run-e2e.mjs local",
"test:dev": "node scripts/run-e2e.mjs dev",
"test:test": "node scripts/run-e2e.mjs test"
},
"keywords": [],
"author": "",
......
import { defineConfig, devices } from '@playwright/test';
import { getE2EEnv } from './projects/dj-carlife-web/config/e2e-env';
/**
* Read environment variables from file.
* https://github.com/motdotla/dotenv
*/
// import dotenv from 'dotenv';
// import path from 'path';
// dotenv.config({ path: path.resolve(__dirname, '.env') });
const e2eEnv = getE2EEnv();
const appProject = process.env.E2E_APP_PROJECT || 'dj-carlife-web';
const testDirs = {
'dj-carlife-web': './projects/dj-carlife-web/tests',
};
/**
* See https://playwright.dev/docs/test-configuration.
*/
export default defineConfig({
testDir: './tests',
/* Run tests in files in parallel */
fullyParallel: true,
/* Fail the build on CI if you accidentally left test.only in the source code. */
testDir: testDirs[appProject as keyof typeof testDirs] || testDirs['dj-carlife-web'],
timeout: 90000,
fullyParallel: false,
forbidOnly: !!process.env.CI,
/* Retry on CI only */
retries: process.env.CI ? 2 : 0,
/* Opt out of parallel tests on CI. */
workers: process.env.CI ? 1 : undefined,
/* Reporter to use. See https://playwright.dev/docs/test-reporters */
workers: 1,
reporter: [['html']],
/* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */
use: {
/* Base URL to use in actions like `await page.goto('')`. */
baseURL: 'http://localhost:3000',
/* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */
baseURL: e2eEnv.baseURL,
trace: 'on-first-retry',
},
/* Configure projects for major browsers */
projects: [
{
name: 'chromium',
use: { ...devices['Desktop Chrome'] },
name: 'edge',
use: { ...devices['Desktop Chrome'], channel: 'msedge' },
},
{
name: 'firefox',
use: { ...devices['Desktop Firefox'] },
},
{
name: 'webkit',
use: { ...devices['Desktop Safari'] },
},
/* Test against mobile viewports. */
// {
// name: 'Mobile Chrome',
// use: { ...devices['Pixel 5'] },
// },
// {
// name: 'Mobile Safari',
// use: { ...devices['iPhone 12'] },
// },
/* Test against branded browsers. */
// {
// name: 'Microsoft Edge',
// use: { ...devices['Desktop Edge'], channel: 'msedge' },
// },
// {
// name: 'Google Chrome',
// use: { ...devices['Desktop Chrome'], channel: 'chrome' },
// },
],
/* Run your local dev server before starting the tests */
// webServer: {
// command: 'npm run start',
// url: 'http://localhost:3000',
// reuseExistingServer: !process.env.CI,
// },
});
import { networkInterfaces } from 'node:os';
export const CURRENT_ENV = 'test';
export const E2E_ACCOUNT = {
username: process.env.E2E_USERNAME,
password: process.env.E2E_PASSWORD,
};
function getLocalIp() {
for (const addresses of Object.values(networkInterfaces())) {
for (const address of addresses || []) {
if (address.family === 'IPv4' && !address.internal) {
return address.address;
}
}
}
return '127.0.0.1';
}
const localHost = process.env.E2E_LOCAL_HOST || getLocalIp();
export const E2E_ENVS = {
local: {
baseURL: `http://${localHost}:8080/dj-carlife-web/#/`,
},
dev: {
baseURL: 'http://192.168.3.191:8543/#/',
},
test: {
baseURL: 'http://frontend.test.glsx.com.cn/dj-carlife-web/#/',
},
} as const;
export type E2EEnvName = keyof typeof E2E_ENVS;
export function getE2EEnv(name = process.env.E2E_ENV || CURRENT_ENV) {
if (name in E2E_ENVS) {
return E2E_ENVS[name as E2EEnvName];
}
throw new Error(
`未知测试环境:${name}。可用环境:${Object.keys(E2E_ENVS).join('、')}。`
);
}
export function getE2EUrl(path: string, name = process.env.E2E_ENV || CURRENT_ENV) {
const e2eEnv = getE2EEnv(name);
return `${e2eEnv.baseURL}${path.replace(/^\/+/, '')}`;
}
export function getE2EAccount() {
if (!E2E_ACCOUNT.username || !E2E_ACCOUNT.password) {
throw new Error('缺少测试账号或密码。请在 .env.local 中配置 E2E_USERNAME 和 E2E_PASSWORD 后再运行测试。');
}
return {
username: E2E_ACCOUNT.username,
password: E2E_ACCOUNT.password,
};
}
import { test as base, expect } from '@playwright/test';
import { getE2EAccount, getE2EUrl } from '../config/e2e-env';
import { login } from '../pages/login.page';
export const test = base.extend({
page: async ({ page }, use) => {
const account = getE2EAccount();
await page.goto(getE2EUrl('login'), { waitUntil: 'commit' });
await login(page, account);
await use(page);
},
});
export { expect };
import { expect, type Page } from '@playwright/test';
export async function waitForLoginPage(page: Page) {
const accountInput = page.getByPlaceholder(/账户|账号/);
const passwordInput = page.getByPlaceholder(/密码/);
const loginButton = page.getByRole('button', { name: /登录/ });
for (let attempt = 0; attempt < 2; attempt += 1) {
try {
await expect(accountInput).toBeVisible({ timeout: 60000 });
await expect(passwordInput).toBeVisible();
await expect(loginButton).toBeVisible();
return;
} catch (error) {
if (attempt === 1) {
throw error;
}
await page.reload({ waitUntil: 'commit' });
}
}
}
export async function login(page: Page, account: { username: string; password: string }) {
await waitForLoginPage(page);
await page.getByPlaceholder(/账户|账号/).fill(account.username);
await page.getByPlaceholder(/密码/).fill(account.password);
await page.getByRole('button', { name: /登录/ }).click();
await expect(page).not.toHaveURL(/\/login/, { timeout: 30000 });
}
import { expect, test } from '@playwright/test';
import { getE2EUrl } from '../../config/e2e-env';
import { waitForLoginPage } from '../../pages/login.page';
test('基础功能:登录页可以正常打开', async ({ page }) => {
await page.goto(getE2EUrl('login'), { waitUntil: 'commit' });
await expect(page).toHaveURL(/\/login/);
await waitForLoginPage(page);
});
import { expect, test } from '../../fixtures/auth';
import { getE2EUrl } from '../../config/e2e-env';
function normalizeLabelText(text: string) {
return text.replace(/\s+/g, '').replace(/[::]+$/, '');
}
test('SAAS-V5.8.6:采购发货页面新增产品ID搜索项和列表字段', async ({ page }) => {
await page.goto(getE2EUrl('purchaseAndDelivery'), { waitUntil: 'commit' });
await expect(page.getByText(/正在加载资源/)).toBeHidden({ timeout: 60000 });
await expect(page).toHaveURL(/purchaseAndDelivery/);
await expect(page.getByRole('button', { name: '查询' })).toBeVisible({ timeout: 60000 });
const searchFields = [
'产品名称',
'产品编码',
'所属分类',
'系列',
'订单编号',
'下单时间',
'下单商户',
'发货状态',
'分配状态',
'采购模式',
'发货主体',
'审核时间',
'发货方',
'发货时间',
'签收状态',
'供应商名称',
'供应商编码',
'产品ID',
];
const searchItems = [];
for (const field of searchFields) {
const label = page.getByText(new RegExp(`^\\s*${field}[::]\\s*$`)).first();
await expect(label, `搜索项中没有找到“${field}”`).toBeVisible({ timeout: 60000 });
const box = await label.boundingBox();
expect(box, `搜索项“${field}”没有可见位置`).not.toBeNull();
searchItems.push({ field, x: box!.x, y: box!.y });
}
const searchLabels = searchItems
.sort((left, right) => (Math.abs(left.y - right.y) < 8 ? left.x - right.x : left.y - right.y))
.map(({ field }) => field);
const signStatusIndex = searchLabels.indexOf('签收状态');
const productIdSearchIndex = searchLabels.indexOf('产品ID');
expect(
productIdSearchIndex,
`“产品ID”搜索项必须紧跟在“签收状态”后面,实际搜索项顺序:${searchLabels.join('、')}`
).toBe(signStatusIndex + 1);
const table = page.locator('.el-table, table').filter({ hasText: '产品名称' }).first();
await expect(table).toContainText('产品名称', { timeout: 60000 });
await expect(table).toContainText('产品ID');
const tableHeaders = await table.locator('.el-table__header-wrapper th .cell, thead th').evaluateAll((elements) =>
elements
.map((element) => element.textContent || '')
.map((text) => text.replace(/\s+/g, '').replace(/[::]+$/, ''))
.filter(Boolean)
);
const productNameIndex = tableHeaders.findIndex((text) => normalizeLabelText(text) === '产品名称');
const productIdTableIndex = tableHeaders.findIndex((text) => normalizeLabelText(text) === '产品ID');
expect(productNameIndex, `列表中没有找到“产品名称”,实际表头:${tableHeaders.join('、')}`).toBeGreaterThanOrEqual(0);
expect(productIdTableIndex, `列表中没有找到“产品ID”,实际表头:${tableHeaders.join('、')}`).toBeGreaterThanOrEqual(0);
expect(
productIdTableIndex,
`“产品ID”列表字段必须紧跟在“产品名称”后面,实际表头顺序:${tableHeaders.join('、')}`
).toBe(productNameIndex + 1);
});
import { existsSync, readFileSync } from 'node:fs';
import { spawnSync } from 'node:child_process';
const envName = process.argv[2];
const rawArgs = process.argv.slice(3);
const appProjects = new Map([
['dj-carlife-web', {
root: 'projects/dj-carlife-web',
suites: new Map([
['basic', 'projects/dj-carlife-web/tests/basic'],
['saas-v5.8.6', 'projects/dj-carlife-web/tests/saas-v5.8.6'],
]),
}],
]);
let suiteName = 'all';
let appProjectName = 'dj-carlife-web';
const extraArgs = [];
for (let index = 0; index < rawArgs.length; index += 1) {
const arg = rawArgs[index];
if (arg === '--app-project') {
appProjectName = rawArgs[index + 1] || '';
index += 1;
continue;
}
if (arg.startsWith('--app-project=')) {
appProjectName = arg.split('=').slice(1).join('=');
continue;
}
if (arg === '--suite') {
suiteName = rawArgs[index + 1] || '';
index += 1;
continue;
}
if (arg.startsWith('--suite=')) {
suiteName = arg.split('=').slice(1).join('=');
continue;
}
extraArgs.push(arg);
}
if (!appProjects.has(appProjectName)) {
console.error('未知测试项目:' + appProjectName + '。可用项目:' + [...appProjects.keys()].join('、') + '。');
process.exit(1);
}
const appProject = appProjects.get(appProjectName);
const suitePath = appProject.suites.get(suiteName);
if (suiteName !== 'all' && !suitePath) {
console.error('未知用例范围:' + suiteName + '。请确认该项目已配置此用例范围。');
process.exit(1);
}
const hasProjectArg = extraArgs.some((arg) => arg === '--project' || arg.startsWith('--project='));
const playwrightArgs = [
'playwright',
'test',
...(hasProjectArg ? [] : ['--project=edge']),
...(suitePath ? [suitePath] : [appProject.root]),
...extraArgs,
];
if (existsSync('.env.local')) {
const lines = readFileSync('.env.local', 'utf8').split(/\r?\n/);
for (const line of lines) {
const trimmed = line.trim();
if (!trimmed || trimmed.startsWith('#') || !trimmed.includes('=')) continue;
const [key, ...valueParts] = trimmed.split('=');
process.env[key.trim()] = valueParts.join('=').trim();
}
}
const result = spawnSync('npx', playwrightArgs, {
stdio: 'inherit',
shell: true,
env: {
...process.env,
...(envName ? { E2E_ENV: envName } : {}),
E2E_APP_PROJECT: appProjectName,
},
});
if (result.error) {
console.error(result.error.message);
}
process.exit(result.status ?? 1);
import { test, expect } from '@playwright/test';
test('has title', async ({ page }) => {
await page.goto('https://playwright.dev/');
// Expect a title "to contain" a substring.
await expect(page).toHaveTitle(/Playwright/);
});
test('get started link', async ({ page }) => {
await page.goto('https://playwright.dev/');
// Click the get started link.
await page.getByRole('link', { name: 'Get started' }).click();
// Expects page to have a heading with the name of Installation.
await expect(page.getByRole('heading', { name: 'Installation' })).toBeVisible();
});
window.E2E_PANEL_SELECT_OPTIONS = {
appProject: [
{ value: 'dj-carlife-web', label: 'D+智享车生活PC' },
],
env: [
{ value: 'test', label: '测试环境' },
{ value: 'dev', label: '开发环境' },
{ value: 'local', label: '本地环境' },
],
suite: [
{ value: 'basic', label: '基础功能' },
{ value: 'saas-v5.8.6', label: 'SAAS-V5.8.6' },
{ value: 'all', label: '全部用例' },
],
browser: [
{ value: 'edge', label: 'Edge' },
{ value: 'all', label: '全部浏览器' },
{ value: 'firefox', label: 'Firefox' },
{ value: 'webkit', label: 'WebKit' },
],
};
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!