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

如何在ES Modules项目中配置TestCafe全局钩子

在ES Modules项目中配置TestCafe全局钩子

核心解决步骤

  • 调整配置文件格式:TestCafe支持ESM格式的配置文件,只需将配置文件命名为.testcaferc.mjs;如果你的项目在package.json中已经设置了"type": "module",也可以直接使用.testcaferc.js。
  • 修正钩子中的测试控制器获取方式:全局钩子的before方法会接收testRun参数,需要从该参数中获取t控制器,不能直接使用全局的t变量。

正确的配置示例

1. 授权Role文件(src/testing/utilities/loginUser.js)

import { Role, Selector, t } from 'testcafe';

export const user = Role('http://localhost:3000/login', async t => {
    await t
        .typeText(Selector('#loginInput'), 'Login')
        .typeText(Selector('#passwordInput'), 'Password')
        .click(Selector('button').withAttribute('data-testid', 'submitButton'));        
});

2. ESM格式的TestCafe配置文件(.testcaferc.mjs)

import { user } from './src/testing/utilities/loginUser.js';

export default {
  hooks: {
    testRun: {
      before: async (testRun) => {
        const t = testRun.testController;
        await t.useRole(user);
      }
    },
  }
};

额外说明

  • 如果你的项目通过package.json的"type": "module"启用ESM,那么配置文件可以保留.js后缀,但确保所有导入路径使用完整的扩展名(比如.js),Node.js的ESM解析要求必须明确扩展名。
  • 全局钩子的testRun.before会在整个测试运行开始前执行一次,如果需要在每个测试用例前执行授权,应该使用test.before钩子:
export default {
  hooks: {
    test: {
      before: async (testRun) => {
        const t = testRun.testController;
        await t.useRole(user);
      }
    },
  }
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 14:40:29