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

Playwright中test外使用await报错:SyntaxError参数列表缺失)

问题描述

测试代码如下:

import { test, expect, chromium } from '@playwright/test';
import * as path from "path";
import fs from "fs-extra";
const INPUT_DIR = path.resolve(__dirname, "./../data");
const items1 = JSON.stringify((await fs.readJson(path.resolve(INPUT_DIR, "items1.json"))));
const expected1 = '0.999999111111';

test("test1", async () => {
  const browser = await chromium.launch({ headless: false });
  const context = await browser.newContext();
  const page = await context.newPage();
  await page.goto('http://localhost:3000');
  expect('abc').toContain('a'); // <-- dummy test
});

执行命令 npx playwright test readJsonAsyncProblem.spec.ts 后出现报错:

SyntaxError: missing ) after argument list
Error: No tests found

之前用await csvtojson时也碰到过同样的问题,把第5行改成同步调用const items1 = JSON.stringify((fs.readJsonSync(path.resolve(INPUT_DIR, "items1.json"))));后测试就能正常运行了。

问题原因与解决方法
  • 核心问题:你在模块的顶级作用域直接使用了await关键字。JavaScript/TypeScript中,await只能在async函数内部使用,顶级作用域的await需要特定环境支持(比如ES模块的顶级await),但Playwright测试默认的CommonJS模块环境不兼容这种写法,导致语法解析失败。
  • 为什么提示“找不到测试”:语法错误会让Node.js无法正确解析整个测试文件,Playwright自然找不到文件里的test测试块,因此抛出No tests found的错误。
  • 解决办法:
    1. 继续使用同步方法:保持你已经验证有效的写法,用fs.readJsonSync这类同步API替代异步版本,避开顶级作用域的await问题。
    2. 将异步逻辑移到测试函数内部:把读取JSON的代码放到test的async回调函数里,这样就能合法使用await:
      import { test, expect, chromium } from '@playwright/test';
      import * as path from "path";
      import fs from "fs-extra";
      const INPUT_DIR = path.resolve(__dirname, "./../data");
      const expected1 = '0.999999111111';
      
      test("test1", async () => {
        // 把异步读取逻辑移到这里
        const items1 = JSON.stringify(await fs.readJson(path.resolve(INPUT_DIR, "items1.json")));
        const browser = await chromium.launch({ headless: false });
        const context = await browser.newContext();
        const page = await context.newPage();
        await page.goto('http://localhost:3000');
        expect('abc').toContain('a');
      });
      
    3. 切换到ES模块模式:如果一定要用顶级await,可以把测试文件后缀改成.mts,或者在项目的package.json里添加"type": "module"配置。不过要注意,这种模式下__dirname会失效,需要用import.meta.url替代,同时要确保Playwright的配置也兼容ES模块。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 10:37:25