Element presence
Loading "Element Presence (🏁 solution)"
Run locally for transcripts
Let's prepare our
<DiscountCodeForm />
for this test case by doing the following:test('removes the applied discount code', async () => {
render(<DiscountCodeForm />)
// Enter a discount code.
const discountInput = page.getByLabelText('Discount code')
await discountInput.fill('EPIC2025')
// Apply the code.
const applyDiscountButton = page.getByRole('button', {
name: 'Apply discount',
})
await applyDiscountButton.click()
// Make sure that it's actually applied.
const discountText = page.getByText('Discount: EPIC2025 (-20%)')
await expect.element(discountText).toBeVisible()
})
All that remains now is to remove this discount code the way a user would. For that, I will first locate the "Remove discount" button by its role
button
and its accessible text:const removeDiscountButton = page.getByRole('button', {
name: 'Remove discount',
})
await removeDiscountButton.click()
And now I will write a regular assertion with
expect.element()
using the .not.toBeInTheDocument()
as the matcher:await expect.element(discountText).not.toBeInTheDocument()
So how does this work?
It's due to the retry mechanism built-in into
expect.element()
, which automatically makes Vitest waitFor
the given assertion. Even if it takes time to remove the discountText
element from the page, our test will wait until that happens and throw if it doesn't.🦉 You can configure the retry options onexpect.element()
by providing them as the second argument to the function:await expect.element(locator, { interval, timeout })
Learn more in the 📜expect.poll()
documentation.