You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

执行testRunner.ts时出现Playwright Test不期望调用test()的错误

问题

我在tests文件夹存放.spec.ts测试文件,testRunner.ts位于上级目录。用tsc构建项目,配置将生成的js文件存入dist文件夹。执行构建后的testRunner.js时,出现错误:

Error: Playwright Test did not expect test() to be called here

已排查以下情况:

  • 未在配置文件中调用test()
  • 未安装多个playwright/test版本
  • 未在配置文件导入的文件中调用test()

作为TypeScript和Playwright新手,不确定还能进行哪些排查。以下是相关文件代码:

testRunner.ts

import { Command } from "commander";
const fs = require('fs'); // no default export in node.js

const executeTests = new Command();
executeTests 
    .requiredOption('-c, --client <clientName>', 'Specify the client name. Eg. -c nbc OR --client nbc')
    .parse(process.argv) // returns an array containing the command line args (client name)

const options = executeTests.opts();
const clientName = options.client.toLowerCase();
const clientTestDataFile = '../clientTestData/testdata_'+clientName+'.json';

if (!fs.existsSync(clientTestDataFile)) {
    console.error('Error: Test data file not found in the test data folder for the client '+clientName+'.');
    process.exit(1);
} else {
    runTests();
   // runTests();
}
const clientTestData = JSON.parse(fs.readFileSync(clientTestDataFile, 'utf-8'));

async function runTests() {
    console.log('test1');
    const { runTest1 } = await import('./tests/tes.spec');
    console.log('test2');
    await runTest1();
   // runTest1();
    //runTest2();
}

tsconfig.json

{
    "compilerOptions": {
      "target": "ES5",
      "module": "CommonJS",
      "sourceMap": true,
      "outDir": "dist"
    }
}

tes.spec.ts

import { expect, test} from "@playwright/test"
//import casualportal_home from "../page/casualportal_home";
//import { create } from "domain";
//import casualportal_cart from "../page/casualportal_cart";
//const testdata= JSON.parse(JSON.stringify(require("../testdata.json")))

export function runTest1() {
    test('Validate if the "Book" button works', async ({ page , baseURL }) => {
        console.log('test() called')
    });
};
解决方案

核心问题是Playwright Test的test()函数不能通过自定义脚本直接调用,它必须由官方测试运行器npx playwright test执行。你的自定义runner逻辑违背了Playwright的运行机制,修正方案如下:

  1. 标准化测试文件
    去掉runTest1导出函数,直接写标准Playwright测试用例:
// tests/tes.spec.ts
import { expect, test} from "@playwright/test"

test('Validate if the "Book" button works', async ({ page , baseURL }) => {
    console.log('test() called')
});
  1. 用环境变量实现客户端数据加载
    通过环境变量传递客户端名称,在测试文件中读取对应数据:
// tests/tes.spec.ts
import { expect, test} from "@playwright/test"
import fs from 'fs';

const clientName = process.env.CLIENT?.toLowerCase() || 'default';
const clientTestData = JSON.parse(fs.readFileSync(`../clientTestData/testdata_${clientName}.json`, 'utf-8'));

test('Validate if the "Book" button works', async ({ page , baseURL }) => {
    console.log('Using client data:', clientName);
    // 这里使用clientTestData编写测试逻辑
});
  1. 重写testRunner调用Playwright命令
    自定义runner仅做参数校验,然后调用Playwright官方测试命令:
// testRunner.ts
import { Command } from "commander";
import { spawn } from 'child_process';
import fs from 'fs';

const executeTests = new Command();
executeTests 
    .requiredOption('-c, --client <clientName>', 'Specify the client name. Eg. -c nbc OR --client nbc')
    .parse(process.argv);

const options = executeTests.opts();
const clientName = options.client.toLowerCase();
const clientTestDataFile = `../clientTestData/testdata_${clientName}.json`;

if (!fs.existsSync(clientTestDataFile)) {
    console.error(`Error: Test data file not found for client ${clientName}.`);
    process.exit(1);
}

// 传递环境变量,调用Playwright测试
const pwProcess = spawn('npx', ['playwright', 'test'], {
    env: { ...process.env, CLIENT: clientName },
    stdio: 'inherit' // 同步输出到终端
});

pwProcess.on('exit', code => process.exit(code || 0));
  1. 构建与运行
    执行tsc构建项目后,运行dist/testRunner.js -c nbc即可,脚本会自动调用Playwright执行对应客户端的测试。

内容的提问来源于stack exchange,提问作者Akshitha Dalpethado

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 22:30:29