Rayrun

What are the pros and cons of using codegen generated locators versus writing them myself in Playwright?

Answer

Sure, you're considering whether to use codegen generated locators or to write them yourself in @playwright/test. Let's break it down.

Codegen Generated Locators

Codegen can be a real time-saver. It generates locators based on recommended strategies, prioritizing role, text, and test id locators. If multiple elements match, it refines the locator, making your tests more resilient and less likely to fail due to locator issues.

Here's an example of how you might use codegen in Playwright:

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

test('codegen example', async ({ page }) => {
  await page.goto('https://ray.run/');
  const locator = page.locator('.my-element');
  await expect(locator).toHaveText('Hello, world!');
});

Writing Your Own Locators

Writing your own locators gives you more control. You can tailor them to your application, and your understanding of your app may lead to more accurate tests.

Here's an example of how you might write your own locator:

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

test('custom locator example', async ({ page }) => {
  await page.goto('https://ray.run/');
  const locator = page.locator('#custom-id');
  await expect(locator).toHaveText('Hello, world!');
});

The Verdict

Your choice depends on your testing experience, your app's complexity, and your testing strategy. Try both and see what works best for you. For more insights, check out Mastering Playwright Test Automation: Your Comprehensive Cheat Sheet.

References

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.