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

如何自定义TestCafe Studio的JS渲染模板以添加自定义导入内容?

修改Convert to JavaScript模板添加自定义导入

TestCafe Studio的Convert to JavaScript功能确实基于预设模板生成输出代码,可按以下步骤修改模板:

  • 完全关闭TestCafe Studio,避免修改的模板被程序覆盖
  • 找到模板存放目录,不同系统默认路径如下:
    • Windows:C:\Program Files\TestCafe Studio\resources\app.asar.unpacked\testcafe\static\code-generation-templates
    • macOS:/Applications/TestCafe Studio.app/Contents/Resources/app.asar.unpacked/testcafe/static/code-generation-templates
    • Linux:/opt/TestCafe Studio/resources/app.asar.unpacked/testcafe/static/code-generation-templates
  • 根据生成代码的类型打开对应模板文件:普通测试用例修改test.js.ejs,测试套件修改fixture.js.ejs
  • 在模板顶部直接添加你需要的导入语句,比如import * as testUtils from './utils/test-helper'、import { UserCenterPage } from './pom/user-center'
  • 保存修改后重启TestCafe Studio,后续转换生成的代码会自动携带你添加的导入内容。
测试运行前执行初始化脚本的实现

要提前导入工具、页面对象并挂载到测试上下文,有两种常用实现方式:

  • Fixture级钩子挂载
    直接在测试套件的before钩子内导入依赖并挂载到上下文对象,所有同套件的测试用例都可以通过t.ctx访问挂载的内容,示例代码如下:
    fixture`用户中心测试套件`
      .page`https://test-site.com/user`
      .before(async ctx => {
        // 导入工具和页面对象
        ctx.testUtils = (await import('./utils/test-helper')).default
        ctx.userCenterPage = (await import('./pom/user-center')).UserCenterPage
        // 可直接执行前置逻辑,比如预置测试数据、获取登录token
      })
    
    test('修改用户昵称测试', async t => {
      await t.typeText(t.ctx.userCenterPage.nicknameInput, '测试用户')
      await t.click(t.ctx.userCenterPage.submitBtn)
      await t.expect(t.ctx.userCenterPage.successTip.exists).ok()
    })
    
  • 全局前置钩子挂载
    如果你需要所有测试套件都能复用导入的内容,可以在TestCafe配置文件.testcaferc.js中配置beforeRun全局钩子,将依赖挂载到Node.js全局对象,所有测试用例都可以直接访问全局挂载的内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 13:27:02