includes assertion in playwright for for CSS and Attribute?

45 Views Asked by At

Here I have a piece of code in Playwright with the ToHaveCSS function which returns the exact value of the mentioned CSS.
Locator:

locator('//label[text()=\'Chat Status\']/following-sibling::*/button')
       Expected string: "rgb(40, 176, 131)"
       Received string: "rgb(40, 176, 131) none repeat scroll 0% 0% / auto padding-box border-box"

As you can see the expected value matches the received value with some extra strings.

Is there any function like string.includes? Which can pass this test. I just want to validate the colour and the other stuff I don't need it. I can still copy and paste the received value to the expected string to pass it. But what if the value dynamically changes and I only want to validate the color? Are there any functions for the playwright to do this?

1

There are 1 best solutions below

1
code_akash On

As per the documentation of inbuilt toHaveCss method from expect:

toHaveCSS Added in: v1.20 Ensures the Locator resolves to an element with the given computed CSS style.

Example:

await expect(locator).toHaveCSS('display', 'flex');

Here, this method will only assert the display value against the expected string 'flex'.

In my sample test using the above toHaveCss, I have something similar as yours (I am not sure why in your case the actual string has other values)

Here is my sample test assertion for background colour that works fine:

test("Check background colour", async ({ page }) => {
  await page.goto("https://the-internet.herokuapp.com");
  expect(page.getByText("A/B Testing")).toHaveCSS("color", "rgb(43, 166, 203)");
});

You can create a helper method for this expectation(remember to use expect) and pass any CSS property name and expected value for assertion.