7

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?

Isen
  • 425
  • 1
  • 5
  • 13

3 Answers3

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
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