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

Playwright React组件测试:本地回调函数始终返回undefined

Playwright React组件测试回调函数返回undefined问题

环境依赖

  • @playwright/experimental-ct-react: 1.49.0
  • @playwright/test: 1.49.0

问题现象

向被测组件传入一个逻辑上始终返回字符串的回调函数,但测试运行时调用该函数,返回结果却是undefined。

问题原因分析

该问题源于Playwright源码中的序列化处理逻辑,关键代码片段如下:

export async function unwrapObject(value: any): Promise<any> {
  return transformObjectAsync(value, async (v: any) => {
    if (isFunctionRef(v)) {
      const result = (...args: any[]) => {
        window.__ctDispatchFunction(v.ordinal, args); // 该行未返回原函数的执行结果
      };
      return { result };
    }
    if (isImportRef(v))
      return { result: await window.__pwRegistry.resolveImportRef(v) };
  });
}

打印测试中实际调用的函数,输出内容如下:

(...args) => {
  window.__ctDispatchFunction(v.ordinal, args);
} 

可见,传入的原回调函数被包装了一层新函数,这个包装函数仅调用了原函数,却没有返回原函数的执行结果,最终导致调用时返回undefined。

可通过仓库playwright-func-errror复现该问题。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 02:22:38