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

TestCafe 2.6.2中addCustomDOMProperties报错及图片加载等待问题

TestCafe中使用addCustomDOMProperties处理懒加载图片的正确用法

1. 解决TypeScript类型扩展问题

你遇到的Property 'nodeName' does not exist on type 'Selector'报错,是因为TypeScript未识别你给Selector添加的自定义属性,需扩展Selector接口定义:

  • 在测试项目中创建testcafe.d.ts类型声明文件,内容如下:
import { Selector } from 'testcafe';

declare module 'testcafe' {
    interface Selector {
        // 定义你要添加的自定义属性类型
        imgComplete: Promise<boolean>;
        nodeName: Promise<string>;
    }
}
  • 确保该文件被TypeScript识别:可放在测试文件同目录,或在tsconfig.json的include数组中添加文件路径。

2. 正确使用addCustomDOMProperties定义自定义属性

给目标Selector添加自定义属性,以获取图片加载状态和元素节点名:

import { Selector } from 'testcafe';

// 定位包含懒加载img的a元素
const lazyImgLink = Selector('a').addCustomDOMProperties({
    // 获取子元素img的加载完成状态
    imgComplete: (el) => {
        const imgElement = el.querySelector('img');
        // 存在img元素则返回其complete属性,否则返回false
        return imgElement ? (imgElement as HTMLImageElement).complete : false;
    },
    // 获取当前元素的nodeName
    nodeName: (el) => el.nodeName
});

此处的el是浏览器端原生DOM元素,可直接调用原生DOM API(如querySelector、nodeName)。

3. 等待图片加载完成后执行点击操作

在测试代码中,先等待自定义的imgComplete属性变为true,再执行点击:

import { t } from 'testcafe';

await t
    // 等待图片加载完成,设置10秒超时避免无限等待
    .wait(lazyImgLink.with({ timeout: 10000 }).imgComplete)
    // 图片加载完成后点击a元素
    .click(lazyImgLink);

额外注意事项

  • 若页面存在多个符合条件的<a>元素,需给选择器添加更精确的定位条件(如类名、属性),确保定位到目标元素。
  • 可结合元素存在性检查提升测试稳定性:
await t
    .expect(lazyImgLink.exists).ok('目标a元素不存在')
    .wait(lazyImgLink.imgComplete)
    .click(lazyImgLink);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 08:38:18