Writing reliable and stable tests is crucial for ensuring a smooth CI/CD pipeline. However, one common mistake many testers make in Playwright is introducing race conditions in their assertions. A small difference in how we write assertions can go a long way in making our tests robust.
In this blog post, we’ll discuss how to properly assert text in Playwright to avoid race conditions and ensure consistent test results.
The Problem: Flaky Assertions
Consider the following Playwright assertion:
expect(await heading.textContent()).toBe('Action');
At first glance, this might seem like a valid assertion. However, this approach can lead to flakiness. Here’s why:
textContent()
fetches the value immediately, meaning it does not wait for the element or page to update.
If the element or page hasn’t yet rendered or updated with the expected text, the test fails unnecessarily.
This can result in intermittent failures, making debugging and test maintenance more difficult.
The Solution: Playwright’s Auto-Retrying Assertions
Playwright provides a better way to assert text values:
await expect(heading).toHaveText('Action');
Why is this better?
✅ Automatic Waiting – Playwright waits for the condition to be met before proceeding.
✅ Handles Dynamic Content – Ensures the test does not fail due to minor timing issues.
✅ More Readable & Maintainable – Clearly expresses the intent.
How Playwright Handles Assertions Under the Hood
Playwright’s expect().toHaveText()
is a polling assertion, meaning it repeatedly checks the condition until it passes or times out. By default, Playwright waits for up to 5 seconds, ensuring the text has had enough time to update before failing the test.
Conclusion
Avoiding race conditions in Playwright assertions is key to reliable test automation. Always use auto-retrying assertions like toHaveText()
instead of textContent()
. This simple adjustment can save hours of debugging and make your test suite robust and stable.
Check out the Video
🔹 Want to see this in action? Check out our latest video where we demonstrate the difference between these approaches:🚀
Useful Links
- Playwright docs
- Join our Discord server
- Subscribe to the Playwright YouTube channel
Have you encountered flaky tests due to race conditions? Let’s discuss in the comments! 👇
Top comments (0)