import * as fs from'fs';
import * as path from'path';
import * as playwright from'playwright';
import * as exceljs from'exceljs';
import * as ts from'typescript';
// 创建一个Excel工作簿const workbook = new exceljs.Workbook();
const worksheet = workbook.addWorksheet('测试报告');
// 定义测试结果的列标题
worksheet.columns = [
{ header: '测试文件', key: 'testFile', width: 30 },
{ header: '测试结果', key: 'testResult', width: 15 },
];
// 获取测试文件夹路径
const testFolderPath = path.join(__dirname, 'tests');
// 读取测试文件夹中的所有文件
const testFiles = fs.readdirSync(testFolderPath);
// 创建一个异步函数,用于执行测试并记录结果到Excel文件
async function runTestsAndRecordResults() {
// 遍历测试文件
for (const testFile of testFiles) {
const testFilePath = path.join(testFolderPath, testFile);
// 解析测试文件
const sourceFile = ts.createSourceFile(
testFilePath,
testFileContent,
ts.ScriptTarget.ES2015,
true
);
// 查找并执行测试函数
findAndExecuteTestFunctions(sourceFile, testFile);
}
// 将Excel文件保存到磁盘
await workbook.xlsx.writeFile('测试报告.xlsx');
}
// 递归查找并执行测试函数
function findAndExecuteTestFunctions(node: ts.Node, testFile: string) {
if (ts.isFunctionDeclaration(node) || ts.isMethodDeclaration(node)) {
const functionName = node.name?.getText();
// 判断函数是否符合条件作为测试函数
if (functionName && isTestFunction(node)) {
// 动态导入测试文件
const testModule = require(path.join(__dirname, 'tests', testFile));
// 执行测试函数
const testResult = testModule[functionName]();
// 记录结果到Excel文件
worksheet.addRow({ testFile, testResult });
}
}
// 递归遍历子节点 ts.forEachChild(node, (childNode) => {
findAndExecuteTestFunctions(childNode, testFile);
});
}
// 判断函数是否符合条件作为测试函数functionisTestFunction(node: ts.FunctionDeclaration | ts.MethodDeclaration) {
// 可根据需要自定义判断条件// 这里简单判断函数名是否以 "test" 开头return node.name?.getText().startsWith('test');
}
// 运行测试并记录结果
runTestsAndRecordResults()
.then(() => console.log('测试执行完毕,结果已记录到文件。'))
.catch((error) => console.error('出现错错误:', error));