The response from @aknuds1 is spot-on, but here's a helpful tip to make things even easier for yourself. You can create a helper function like this one, which will return true
if the element is visible and false
otherwise.
function checkVisibility(page, selector, timeout = 150) {
return new Promise((resolve) => {
page.waitForSelector(selector, {visible: true, timeout}).then(() => {
resolve(true);
}).catch(() => {
resolve(false);
});
});
}
How to Use:
For plain JavaScript with Puppeteer
let isVisible = await checkVisibility(page, selector)
isVisible = await checkVisibility(page, selector, 300)
If you are using Jest or another testing framework
expect(await checkVisibility(page, selector)).toBeTrue();
In the case of Jest (or most other frameworks), you can take it a step further by creating a custom matcher to enhance the existing ones. (https://jestjs.io/docs/expect#expectextendmatchers)
expect.extend({
async toHaveVisible(page, selector, timeout = 150) {
let isVisible = await checkVisibility(page, selector, timeout);
if (isVisible) {
return {
message: () => `expected ${selector} not to be visible`,
pass: true
};
} else {
return {
message: () => `expected ${selector} to be visible`,
pass: false
};
}
}
});
await expect(page).toHaveVisible(selector);
await expect(page).not.toHaveVisible(anotherSelector);
await expect(page).not.toHaveVisible(yetAnotherSelector, 300);