I have an element that has this style color: #dc7709 and I want to check if that element's text is of that color. How do I do that with Puppeteer or playwright?
Asked
Active
Viewed 8,172 times
3 Answers
6
You can use window.getComputedStyle. Notice that it will return an rgb
value:
assert(await page.$eval('span', e => getComputedStyle(e).color)).toBe('rgb(220, 119, 9)');

hardkoded
- 18,915
- 3
- 52
- 64
-
Hi, do you know how we should use it when we need the color after the **:hover** css effect ? Thanks – theospace Jan 07 '22 at 09:45
0
expect(await page.$eval('span', e => getComputedStyle(e).caretColor)).toBe('rgb(220, 119, 9)');
The above can also be used, change the rgb value as per requirement.

buddemat
- 4,552
- 14
- 29
- 49
0
If you're lazy-loading styles, wait for the stylesheet to load first:
// playwright.spec.ts
test.only('should style alert messages', async ({ page }) => {
const alert = page.locator('.alert-primary').first();
const initialColor = await alert.evaluate((el) => {
return getComputedStyle(el).backgroundColor;
});
console.log(initialColor);
await page.waitForResponse(
'https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css'
);
const styledColor = await alert.evaluate((el) => getComputedStyle(el).backgroundColor);
console.log(styledColor);
});
As the initialColor
and styledColor
may differ:
rgba(0, 0, 0, 0)
rgb(212, 237, 218)
You can then convert to hex for your test assertion:
expect(rgbToHex(styledColor) === '#dc7709');

vhs
- 9,316
- 3
- 66
- 70