Asserting text that is still changing

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.

Status: Not started

Order confirmation

Every order gets a new random ID.