In the last part, we saw some useful assertions from Playwright. These assertions help in a lot of ways and to assert some things on the web app. Since Playwright has a rich set of features, so these assertions are also one useful addition to that armoury.
Again, the disclaimer – these assertions are provided by the default test runner given by Playwright. So we’d consider that only, not Jest.
toHaveCount()
This assertion allows us to assert that a given locator has a exact no. of DOM nodes. A good example would be, counting the no of options from a drop down, and asserting that there are N options.
e.g.
const list = page.locator('ul > li');
await expect(list).toHaveCount(3);
Syntax :
expect(locator).toHaveCount(n);
toHaveJSProperty()
This assertion allows to assert if a given element has a required JS Property. Note that this property can be of a primitive type as well as a plain serializable JavaScript object.
Syntax :
expect(locator).toHaveJSProperty('loaded',true);
toHaveScreenshot()
This assertion takes two consecutive locator screenshots and then compares the last one with the expected screenshot.
Syntax :
expect(locator).toHaveScreenshot();
toHaveText()
This assertion is useful for matching a certain DOM element if they have certain text. The assertion will assert that the locator under question points to element with the expected text.
Syntax :
expect(locator).toHaveText(expected_text);
toHaveValue()
This assertions allows us to assert whether a given input element is having certain values. Let’s say we want to see if an input value has an integer value, then we can use this assertion
const locator = page.locator('input[type=number]');
await expect(locator).toHaveValue(/[0-9]/);
Syntax :
expect(locator).toHaveValue(expected_value);
toHaveTitle()
This is a page level assertion and we can assert whether a given web page has a specific title,
await expect(page).toHaveTitle(expected_title);
toHaveURL()
Asserts that the page contains the specific URL.
Syntax:
expect(page).toHaveURL(url);
toBeOK()
Asserts that the response code of the API is under the range 200..299
status.
expect(response).toBeOK();
So these are the assertions provided in Playwright. You can use this link by LambdaTest if you want to see code pieces for all the important assertions in Playwright.