Rayrun

What are some best practices for writing resilient tests with @playwright/test?

Answer

Sure, let's dive into some best practices for writing resilient tests with @playwright/test.

Test User-Visible Behavior

First off, focus on testing user-visible behavior, not implementation details. Your tests should confirm that the application works for end users. Avoid relying on things like function names or CSS classes that users won't see or use.

Isolate Your Tests

Next, make your tests as isolated as possible. Each test should run independently with its own local storage, session storage, data, cookies, etc. This improves reproducibility and debugging, and prevents cascading test failures.

Use Before and After Hooks

To avoid repetition, use before and after hooks. For example, you can add a before hook to run a part of your test before each test, like navigating to a URL or logging in.

import { test } from '@playwright/test';

test.beforeEach(async ({ page }) => {
  await page.goto('https://ray.run');
});

test('my test', async ({ page }) => {
  // Your test code here.
});

Use Resilient Locators

Use locators that can withstand changes in the DOM structure. Playwright provides several ways to generate locators, including chaining and filtering locators by text or by another locator.

const submitButton = page.locator('text="Submit"');

Use Web First Assertions

Finally, when writing assertions, use web first assertions like toBeVisible(), which waits until an expected condition is met, rather than isVisible(), which returns immediately.

await expect(page.locator('text="Submit"')).toBeVisible();

For more tips, check out Mastering Playwright Test Automation: Your Comprehensive Cheat Sheet. Happy testing!

Thank you!
Was this helpful?
Still have questions?

If you still have questions, please ask a question and I will try to answer it.

Related Questions

TwitterGitHubLinkedIn
AboutQuestionsDiscord ForumBrowser ExtensionTagsQA Jobs

Rayrun is a community for QA engineers. I am constantly looking for new ways to add value to people learning Playwright and other browser automation frameworks. If you have feedback, email luc@ray.run.