Skip to main content

Code injection

It can be convenient to inject Javascript into a page to ensure screenshots' consistency.

For example, the screenshot could be taken when the assets are not fully loaded and induce a flaky test.

In our integrations, we execute the following functions in the tested pages and wait for their resolution before taking a screenshot.

Inject styles in a page

Injected style to hide elements and fix unstable rendering.

function injectStyles(document) {
const css = document.createElement("style");
css.type = "text/css";
css.textContent = cssText;
document.body.appendChild(css);
}

Ensure no busy

Check if there is [aria-busy="true"] element on the page. It prevent in progress loaders to be displayed.

async function ensureNoBusy() {
const checkIsVisible = (element) =>
Boolean(
element.offsetWidth ||
element.offsetHeight ||
element.getClientRects().length
);

return [...document.querySelectorAll('[aria-busy="true"]')].every(
(element) => !checkIsVisible(element)
);
}

Wait for fonts

Wait for all fonts to be loaded.

function waitForFonts() {
return document.fonts.status === "loaded";
}

Wait for images

Wait for all images to be loaded.

async function waitForImages() {
return Promise.all(
Array.from(document.images)
.filter((img) => !img.complete)
.map(
(img) =>
new Promise((resolve) => {
img.onload = img.onerror = resolve;
})
)
);
}