3

我想在运行任何 TestCafe 测试之前等待页面中的 Web 组件升级(换句话说,WebComponentsReady在运行测试之前等待事件)。做这个的最好方式是什么?

4

1 回答 1

3

引发事件后,TestCafe 开始在页面上执行任何操作DOMContentReady。如我所见,该WebComponentsReady事件可以在DOMContentReady. TestCafe 允许您使用 ClientFunction 等待浏览器中的某些事件:

const waitForWebComponentsReady = ClientFunction(() => {
    return new Promise(resolve => {
        window.addEventListener('WebComponentsReady', resolve);
    });
});

await waitForWebComponentsReady();

但是请注意,TestCafe 不能保证在WebComponentReady引发事件之前会执行此代码。因此,此 Promise 将无法解决。

作为一种解决方案,您可以找到另一种方法来确定是否加载了所需的 Web 组件。例如,您可以检查页面上是否可见某些元素:

await t.expect(Selector('some-element').visible).ok();

同时,TestCafe 有一个功能建议,在页面初始化脚本之前添加执行自定义脚本的能力。实现该功能后,您将能够使用这样的代码:

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();
    });
于 2017-09-06T16:05:03.200 回答