Check the site works correctly (part 2)
Learn how to extract data from a page.
To test if your application works properly you can rely a lot on actions. E.g. if you click on something it has to be visible.
But often you also need to query data from the DOM to check for correctness.
Let's say you add an item to a cart and want to check that the correct item is in cart, while being on the product detail page you can query the product title with locator.innerText().
const productHeading = page.getByRole("heading", { level: 2 });
const productName = await productHeading.first().innerText();
And assert that the product is in cart on the next page.
const cartContainer = page.getByTestId("cart");
await expect(cartContainer.getByText(`1x, ${productName}`)).toBeVisible();
Sometimes you must evaluate not one but many values.
Methods like allInnerTexts or allTextContents are invaluable when dealing with locators mathcing multiple DOM elements.
// Get all the inner text values of all elements matching getByTestId('price')
const allPrices = await productLinks.getByTestId("price").allInnerTexts();
// "100.0", "250", "1234", ...
Take your previously recorded 'add to cart' test case and validate that:
- the correct items are in the cart (check for their product names).
- the sum of items in the cart is the correct total amount.
- 💡 Tip: look out for
data-testidattributes. They'll make things easier to test.
💡 If you're stuck, find a working example on GitHub.