Changing Text
Text that updates by itself over time, and text that is different on every run.
Snapshots go stale
textContent() reads the text once, at that instant. If the page has not caught up yet, the test fails, and only sometimes. That is the classic flaky test:
// ❌ Reads the status once. Fails whenever the job is not done yet.
const status = await page.getByTestId('job-status').textContent();
expect(status).toBe('Passed');A web-first assertion such as toHaveText() keeps reading until the text matches or the timeout runs out:
// ✅ Retries until the status reads "Passed".
await page.getByRole('button', { name: 'Run job' }).click();
await expect(page.getByTestId('job-status')).toHaveText('Queued');
await expect(page.getByTestId('job-status')).toHaveText('Passed');Rule of thumb: await expect(locator)… waits; expect(await locator.something()) does not.
Text that is different every run
Generated values such as IDs, dates and totals cannot be hard-coded. Assert their format with a regular expression:
await page.getByRole('button', { name: 'Place order' }).click();
await expect(page.getByTestId('order-confirmation')).toHaveText(
/^Order ORD-\d{6} confirmed$/
);Reuse the value later in the test
Once the assertion has passed, the text is stable, so it is now safe to read it and pull out the part you need:
const text = await page.getByTestId('order-confirmation').textContent();
const orderId = text!.match(/ORD-\d{6}/)![0];Job status
After you click, the status changes by itself: Queued, then Running, then Passed, over about 3.5 seconds.
Order confirmation
Every order gets a new random ID.
Related exercises
- Dynamic ElementsBeginnerAppear & DisappearWait for elements to appear and disappear, without a single fixed sleep.
- Dynamic ElementsIntermediateProgress BarWait for a value to reach a threshold, then act at the right moment.
- Dynamic ElementsAdvancedFlaky LabMake tests that pass every time, then prove it by running them many times.
Read the guide: Playwright auto-waiting: how to fix flaky tests