Thursday, May 1, 2025

Testing meta tags in playwright

In this example we will explore how to get meta tag information in Playwright. Testing meta tags with Playwright involves using the browser automation tool to navigate to a page and then evaluate the content of meta tags in the HTML. Meta tags are part of the <head> section of an HTML document and include elements like <meta name="description" content="...">, <meta property="og:title" content="...">, etc.

Testing meta tags in playwright


Here’s a detailed explanation and step-by-step guide on how to do this:


Example to get meta tag information


const { test, expect } = require('@playwright/test');

test('should have correct meta description tag', async ({ page }) => {
  await page.goto('/');

  // Get the meta description content
  const metaDescription = await page.locator('head > meta[name="description"]').getAttribute('content');

  // Assert that it matches the expected value
  expect(metaDescription).toBe('This is the expected description of the page');
});

test('should have correct Open Graph title', async ({ page }) => {
  await page.goto('/');

  const ogTitle = await page.locator('head > meta[property="og:title"]').getAttribute('content');

  expect(ogTitle).toBe('Expected OG Title');
});

test('head has canonical', async ({ page }) => {
  await page.goto('/')
  const metaDescription = page.locator('link[rel="canonical"]');
  await expect(metaDescription).toHaveAttribute('href', pageURL);
})


test('head has description', async ({ page }) => {
  await page.goto('/')
  const metaDescription = page.locator('meta[name="description"]');
  await expect(metaDescription).toHaveAttribute('description');
})


No comments:

Post a Comment