How toTest meta tags using Playwright

Testing that our web renders the correct meta tags can help us ensure we're not missing any tag which could affect our SEO score.

We can use Playwright to easily test them, first in a utils.ts file create the following helpers:

import type { Page } from "@playwright/test"; export function metatag(page: Page, name: string) { return page.locator(`head > meta[name="${name}"]`); } export function openGraph(page: Page, name: string) { return page.locator(`head > meta[property="og:${name}"]`); } export function twitterCard(page: Page, name: string) { return page.locator(`head > meta[name="twitter:${name}"]`); }

These will help use quickly find any meta tag, Open Graph tag or Twitter Card tag, for example if we wanted to test that <meta name="description" content="something here" /> is on the page we can write our test:

import { expect } from "@playwright/test"; test(`meta[name="description"]`, async ({ page }) => { await expect( metatag(page, "description").getAttribute("content"), ).resolves.toBe("something here"); });

We can similarly do the same for Open Graph and Twitter Card tags now.

test("Open Graph", async ({ page }) = >{ await expect( openGraph(page, "title").getAttribute("content") ).resolves.toBe("The page title for FB"); }); test("Twitter Card", async ({ page }) = >{ await expect( twitterCard(page, "title").getAttribute("content") ).resolves.toBe("The page title for Twitter"); });

With these helpers you can now ensure your web is setting the correct meta tags and that you're not missing any required one.