'How to check with puppeteer or playwright if an element is of a specific color?

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?



Solution 1:[1]

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.

Solution 2:[2]

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/[email protected]/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');

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 buddemat
Solution 2 vhs