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

使用TypeScript在TestCafe实现自定义动作报错:selectFromDropdown不是函数

问题分析与修复方案

错误根源

你遇到的TypeError: testcafe_1.t.customActions.selectFromDropdown is not a function,核心来自三个问题:TypeScript类型声明未正确生效、TestCafe配置文件语法不符合规范、测试用例调用异步方法不规范。


修复步骤

1. 修正TypeScript类型声明文件(definitions.d.ts)

原文件的类型扩展方式错误,需要直接扩展TestCafe的TestController接口,让TypeScript识别t.customActions的类型:

// definitions.d.ts
import { Selector, TestControllerPromise } from 'testcafe';

declare module 'testcafe' {
    interface TestController {
        customActions: {
            selectFromDropdown: (dropdownSelector: Selector) => TestControllerPromise;
        };
    }
}

同时在tsconfig.json中配置include,确保TypeScript能识别这个声明文件:

// tsconfig.json
{
  "compilerOptions": {
    "target": "ES2020",
    "module": "CommonJS",
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true
  },
  "include": [
    "tests/**/*",
    "definitions.d.ts"
  ]
}

2. 修正TestCafe配置文件(.testcaferc.ts)

原配置混用了CommonJS和ES模块语法,且错误将类型声明文件加入测试源路径,修正后:

// .testcaferc.ts
import { Selector, TestController } from 'testcafe';

export default {
    browsers: ["chrome"],
    src: ["tests/**/*.ts", "tests/**/*.feature"],
    hostname: "localhost",
    customActions: {
        async selectFromDropdown(this: TestController, dropdownSelector: Selector) {
            await this.click(dropdownSelector);
        }
    }
};

注意:

  • 用export default替代module.exports,符合TypeScript ES模块规范
  • 显式指定this类型为TestController,确保内部能正确调用TestCafe的内置动作
  • 移除src中的definitions.d.ts,它不需要被当作测试源文件

3. 修正测试用例调用逻辑

自定义动作是异步函数,必须添加await才能执行:

// 01_basic.ts
import { Selector, t } from 'testcafe';
import { startPage } from '../../../pages/start-page';

const startSettings = startPage.getStartSettings();

fixture('11-01 - Customercard SMS, functionality')
    .beforeEach(async () => {
        await startPage.selectPage(startPage.customerCardPageButton);   
    });

test('00 - Custom action click', async (t) => {
   await t.customActions.selectFromDropdown(Selector('#dropdownSelector'));
})

4. 依赖与运行检查

确保已安装必要依赖:

npm install typescript @types/testcafe --save-dev

保持原运行命令不变即可:

npx testcafe chrome .\tests\01_basic.ts --test "00 - Custom action click" 

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 22:07:34