每个测试中的测试控制器实例 (t) 都不同,因此您不能以这种方式对其进行修补。
关于您描述的两种情况,请尝试以下方法:
场景 1
使用您需要重用的操作创建辅助函数。您可以在单独的文件中定义帮助程序,然后在需要这些功能时将此文件导入测试:
helpers.js
import { t } from 'testcafe';
export async function type(selector, txt, opts) => {
await t
.click(selector)
.typeText(selector, txt, opts);
}
test.js
import { Selector } from 'testcafe';
import { type } from './helpers.js';
fixture `My Fixture`
.page `https://devexpress.github.io/testcafe/example/`;
test('My Test', async t => {
await type(Selector('#element'), 'text', { replace: true });
});
还请注意,t.typeText 操作会在输入文本之前单击目标输入。您不需要单独的单击操作来聚焦输入。
有关辅助函数的更多信息,请参阅Create Helpers。
我们计划支持自定义操作,以便在未来版本中更好地解决您的用例。详情请见this GitHub issue。
场景 2
TestCafe 可以将自定义脚本注入到测试运行、测试或夹具期间访问的每个页面。这些脚本被注入<head> 标签并以通常的方式执行。
使用您需要注入的脚本创建一个文件:
script.js
window.addEventListener('DOMContentLoaded', function () {
// this code runs on each page when it is loaded
});
然后inject these scripts 使用以下方法之一:
命令行界面
testcafe chrome test.js --client-scripts script.js
编程界面
runner.clientScripts('script.js');
配置文件
{
"clientScripts": "script.js"
}
有关脚本注入的更多信息,请参阅Inject Scripts into Tested Pages。