What is the best way to wait for 'WebComponentsReady' event in TestCafe?

1.2k views Asked by At

I want to wait for web components in the page to upgrade before running any TestCafe tests (In other words, wait for WebComponentsReady event before running tests). What is the best way to do this?

1

There are 1 answers

0
Alexander Moskovkin On

TestCafe starts to execute any action on the page after the DOMContentReady event is raised. As I see, the WebComponentsReady event can be raised before DOMContentReady. TestCafe allows you to wait for some events in the browser by using ClientFunction:

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

await waitForWebComponentsReady();

However, note that TestCafe can't guarantee that this code will be executed before the WebComponentReady event is raised. As a result, this Promise will not be resolved.

As a solution, you can find another way to identify if the required Web Component is loaded. For example, you can check that some element is visible on the page:

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

Meanwhile, TestCafe has a feature suggestion to add the capability to execute a custom script before page initialization scripts. You will be able to use code like this when the feature is implemented:

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();
    });