Rayrun

How do I use Playwright to verify if a link leads to the correct URL?

Answer

Validating Links with Playwright

You can easily validate links in your code using Playwright's locators and assertions.

First, locate the link by its text content using the getByText() method. For instance, to find a link named "Ray", use:

await page.getByText('Ray');

If your links have specific attributes like href, use getByRole() or getByTestId() with filtering options:

await page.getByRole('link', { name: 'Ray' });

To verify the link leads to the right site, click on it and check the resulting URL. Here's how:

const link = await page.getByText('Ray');
await link.click();

const currentUrl = await page.url();
const expectedUrl = 'https://ray.run/';

if (currentUrl === expectedUrl) {
  console.log('The link leads to the correct site.');
} else {
  console.log('The link does not lead to the correct site.');
}

In this example, we first click on the located link using .click(). Then we retrieve the current URL using .url() and compare it with the expected URL.

Remember to replace 'Ray' with your desired link name and adjust the expected URL accordingly.

For more on Playwright, 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 Discord Threads

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.