Creating custom assertions in Playwright is a breeze, thanks to its flexible expect
function. You can define your own matchers that reflect your specific testing needs.
To define a custom matcher, you'll need to create a new method on the expect
object. This method should take one or more arguments and return either true or false, depending on whether the assertion passes or fails.
Here's an example of a custom matcher that checks if an element has a certain class name:
expect.extend({
toHaveClass: async (element, className) => {
const classes = await element.getAttribute('class');
return {
pass: classes.split(' ').includes(className),
message: () => `Expected ${classes} to include ${className}`,
};
},
});
Once you've defined your custom matcher, you can use it in your tests just like any other matcher provided by Playwright. Here's an example:
test('example test', async ({ page }) => {
await page.goto('https://ray.run');
const button = await page.$('#my-button');
await expect(button).toHaveClass('active');
});
In this test, we navigate to ray.run
and find an element with ID my-button
. We then use our custom matcher toHaveClass
to check whether this button has class active
.
By defining your own matchers tailored for your specific testing needs, you can write more expressive tests that are easier to read and maintain over time. Happy testing!
If you still have questions, please ask a question and I will try to answer it.
Rayrun is a community for QA engineers. I am constantly looking for new ways to add value to people learning Playwright and other browser automation frameworks. If you have feedback, email [email protected].