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

Viewed 3956

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?

3 Answers

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)');
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.

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');
Related