我的需求:使用 Playwright 编写自动化测试脚本,并将测试结果保存到 JSON 文件中。
写一个 Next.js API 接口,用于返回这些测试结果。
1. 安装 Playwright
首先,安装 Playwright:
npm install playwright
2. 编写测试脚本
Playwright 测试脚本示例,包含 5 个测试用例,其中有成功和失败的场景。
测试脚本 (playwright-test.js)
const { test, expect } = require('@playwright/test');
const fs = require('fs');
const path = require('path');
// 定义存储测试结果的路径
const resultsPath = path.join(__dirname, 'test-results.json');
let testResults = [];
// 在每次测试后保存结果
test.afterEach(async ({}, testInfo) => {
const result = {
testName: testInfo.title,
status: testInfo.status, // 'passed' 或 'failed'
duration: testInfo.duration,
errors: testInfo.errors, // 错误信息(如果有)
timestamp: new Date().toISOString(),
};
testResults.push(result);
// 将结果写入 JSON 文件
fs.writeFileSync(resultsPath, JSON.stringify(testResults, null, 2));
});
// 测试 1:检查 example.com 的标题
test('Check title of example.com', async ({ page }) => {
await page.goto('https://example.com');
await expect(page).toHaveTitle('Example Domain'); // 这个测试会通过
});
// 测试 2:检查 example.com 的标题(故意失败)
test('Check wrong title of example.com', async ({ page }) => {
await page.goto('https://example.com');
await expect(page).toHaveTitle('Wrong Title'); // 这个测试会失败
});
// 测试 3:检查 the-internet.herokuapp.com 的登录页面标题
test('Check title of the-internet.herokuapp.com login page', async ({ page }) => {
await page.goto('https://the-internet.herokuapp.com/login');
await expect(page).toHaveTitle('The Internet'); // 这个测试会通过
});
// 测试 4:检查 the-internet.herokuapp.com 的登录按钮是否存在
test('Check login button on the-internet.herokuapp.com', async ({ page }) => {
await page.goto('https://the-internet.herokuapp.com/login');
const loginButton = await page.$('button[type="submit"]');
await expect(loginButton).toBeTruthy(); // 这个测试会通过
});
// 测试 5:检查 the-internet.herokuapp.com 的不存在元素(故意失败)
test('Check non-existent element on the-internet.herokuapp.com', async ({ page }) => {
await page.goto('https://the-internet.herokuapp.com/login');
const nonExistentElement = await page.$('button[type="nonexistent"]');
await expect(nonExistentElement).toBeTruthy(); // 这个测试会失败
});
3. 运行测试
运行以下命令来执行测试脚本:
npx playwright test playwright-test.js
4. 生成的 test-results.json 文件
运行测试后,test-results.json
文件的内容可能如下:
[
{
"testName": "Check title of example.com",
"status": "passed",
"duration": 1234,
"errors": [],
"timestamp": "2025-02-05T12:34:56.789Z"
},
{
"testName": "Check wrong title of example.com",
"status": "failed",
"duration": 5678,
"errors": [
{
"message": "Expected: 'Wrong Title'\nReceived: 'Example Domain'"
}
],
"timestamp": "2025-02-05T12:34:56.789Z"
},
{
"testName": "Check title of the-internet.herokuapp.com login page",
"status": "passed",
"duration": 2345,
"errors": [],
"timestamp": "2025-02-05T12:34:56.789Z"
},
{
"testName": "Check login button on the-internet.herokuapp.com",
"status": "passed",
"duration": 3456,
"errors": [],
"timestamp": "2025-02-05T12:34:56.789Z"
},
{
"testName": "Check non-existent element on the-internet.herokuapp.com",
"status": "failed",
"duration": 4567,
"errors": [
{
"message": "expect(received).toBeTruthy()\n\nReceived: null"
}
],
"timestamp": "2025-02-05T12:34:56.789Z"
}
]
5. 创建 Next.js API 接口
在 Next.js 项目中,创建一个 API 路由来读取 test-results.json 文件并返回测试结果。
项目结构
my-nextjs-app/
├── pages/
│ ├── api/
│ │ └── test-results.js
├── test-results.json
├── package.json
└── ...
Next.js API 路由 (pages/api/test-results.js)
import fs from 'fs';
import path from 'path';
export default function handler(req, res) {
// 读取测试结果文件
const resultsPath = path.join(process.cwd(), 'test-results.json');
try {
const data = fs.readFileSync(resultsPath, 'utf8');
const testResults = JSON.parse(data);
// 返回测试结果
res.status(200).json({ success: true, data: testResults });
} catch (error) {
console.error('Error reading test results:', error);
res.status(500).json({ success: false, message: 'Failed to read test results' });
}
}
6. 运行 Next.js 项目
1、启动 Next.js 项目:
npm run dev
2、访问 API 接口:
打开浏览器或使用工具(如 Postman)访问以下 URL:
http://localhost:3000/api/test-results