我想在运行任何TestCafe测试之前等待页面中的Web组件升级(换句话说,在运行测试之前等待WebComponentsReady
事件)。这样做的最佳方式是什么?
答案 0 :(得分:2)
在引发DOMContentReady
事件后,TestCafe开始在页面上执行任何操作。如我所见,WebComponentsReady
事件可以在DOMContentReady
之前提升。
TestCafe允许您使用ClientFunction等待浏览器中的某些事件:
const waitForWebComponentsReady = ClientFunction(() => {
return new Promise(resolve => {
window.addEventListener('WebComponentsReady', resolve);
});
});
await waitForWebComponentsReady();
但请注意,TestCafe无法保证在引发WebComponentReady
事件之前执行此代码。结果,这个承诺将无法解决。
作为解决方案,您可以找到另一种方法来确定是否加载了所需的Web组件。例如,您可以检查页面上是否显示某些元素:
await t.expect(Selector('some-element').visible).ok();
与此同时,TestCafe向add the capability to execute a custom script before page initialization scripts提供了一项功能建议。在实现该功能时,您将能够使用这样的代码:
import { ClientFunction } from 'testcafe';
const initScript = `window.addEventListener('WebComponentsReady', () => window.WebComponentsLoaded = true);`;
fixture `My Fixture`
.page `http://example.com`
.addScriptToEachPage(initScript)
.beforeEach(async t => {
await t.expect(ClientFunction(() => window.WebComponentsLoaded)()).ok();
});