🔥 All-Access Pass — $199 USD (Regular $499) · Unlock all 2,836 Astro themes ➔
komal.nakrani
Get All-Access Pass ($199)
ThemesCategoriesDocsBlogTips & TricksPricingGet All-Access Pass ($199)
Astro Fundamentals••By Komal Nakrani

Astro Testing: Vitest, Playwright and the Container API

Astro testing tools that work: astro check for types, Vitest for logic, the Container API for components, Playwright for end-to-end, plus a11y and link checks.

#Astro#Testing#Vitest#Playwright#CI

Astro testing usually takes four layers: astro check for type errors, Vitest for plain TypeScript logic and component output (using Astro’s Container API), Playwright for end-to-end tests against the built site, and automated accessibility and link checks. Each layer catches a different class of bug, and none of them needs much setup.

This guide lists the tools, shows the minimum config for each in an Astro 7 project, and suggests how much testing a typical content site really needs.

Key Takeaways

  • astro check is the cheapest test you can add. Put it in your build script.
  • Vitest runs with Astro’s Vite config via getViteConfig() from astro/config.
  • The Container API (experimental_AstroContainer from astro/container) renders .astro components to HTML strings in unit tests.
  • Playwright tests the real built output served by astro preview.
  • Axe-based accessibility checks and a link checker catch problems unit tests never see.

What to test on an Astro site

Most Astro sites are content sites, so the risky parts are not complex state but:

  • Broken builds from bad frontmatter or type errors.
  • Helper functions: date formatting, slugs, sorting, reading time.
  • Components rendering the wrong markup for edge cases (no image, long title, empty list).
  • Pages that 404, redirects that loop, links that point nowhere.
  • Accessibility regressions: missing alt text, unlabeled buttons, low contrast.
  • Server features, if you have them: endpoints, actions, middleware.

Match the tool to the risk. You rarely need 100% unit coverage on a marketing site, but a broken contact form or a missing page costs real money.

Layer 1: astro check for types and templates

npm install --save-dev @astrojs/check typescript
npx astro check

astro check type-checks .astro, .ts and framework files, including Astro.props and content collection types. Make it part of the build:

// package.json (excerpt)
{
  "scripts": {
    "build": "astro check && astro build",
    "test": "vitest run",
    "test:e2e": "playwright test"
  }
}

Combined with a Zod schema on your collections, this catches most content mistakes before deploy. The astro check command tip lists its flags.

Layer 2: Vitest for logic

Vitest is the natural unit test runner for Astro because both are built on Vite. Astro’s getViteConfig() makes Vitest resolve imports, aliases and plugins the same way your site does:

npm install --save-dev vitest
// vitest.config.ts
/// <reference types="vitest/config" />
import { getViteConfig } from 'astro/config';

export default getViteConfig({
  test: {
    include: ['src/**/*.test.ts'],
  },
});

Test plain helpers directly:

// src/lib/reading-time.ts
export function readingTime(text: string, wpm = 220): number {
  const words = text.trim().split(/\s+/).filter(Boolean).length;
  return Math.max(1, Math.round(words / wpm));
}
// src/lib/reading-time.test.ts
import { describe, expect, it } from 'vitest';
import { readingTime } from './reading-time';

describe('readingTime', () => {
  it('never returns zero', () => {
    expect(readingTime('')).toBe(1);
  });

  it('rounds to whole minutes', () => {
    expect(readingTime('word '.repeat(660))).toBe(3);
  });
});

Run npx vitest for watch mode. The Vitest tip covers environment options and mocking astro:content.

Layer 3: the Container API for components

To test what an .astro component renders, use the Container API. It renders a component to an HTML string without starting a server:

---
// src/components/PostCard.astro
interface Props {
  title: string;
  href: string;
  draft?: boolean;
}
const { title, href, draft = false } = Astro.props;
---
<article class="card">
  <a href={href}>{title}</a>
  {draft && <span class="badge">Draft</span>}
</article>
// src/components/PostCard.test.ts
import { experimental_AstroContainer as AstroContainer } from 'astro/container';
import { expect, test } from 'vitest';
import PostCard from './PostCard.astro';

test('shows a draft badge only for drafts', async () => {
  const container = await AstroContainer.create();

  const published = await container.renderToString(PostCard, {
    props: { title: 'Hello', href: '/blog/hello/' },
  });
  expect(published).toContain('href="/blog/hello/"');
  expect(published).not.toContain('Draft');

  const draft = await container.renderToString(PostCard, {
    props: { title: 'Hello', href: '/blog/hello/', draft: true },
  });
  expect(draft).toContain('Draft');
});

renderToString also accepts slots, params, locals and a request, so you can test layouts and endpoints too. To render framework components inside, register their renderer with container.addServerRenderer(). The API is still marked experimental, so pin your Astro version in tests and check release notes on upgrade. The Container API explainer goes further.

Layer 4: Playwright for end-to-end tests

End-to-end tests load real pages in real browsers. Test the built site, not the dev server, so you catch production-only problems:

npm init playwright@latest
// playwright.config.ts
import { defineConfig } from '@playwright/test';

export default defineConfig({
  testDir: './tests',
  webServer: {
    command: 'npm run build && npm run preview',
    url: 'http://localhost:4321',
    reuseExistingServer: !process.env.CI,
    timeout: 120_000,
  },
  use: { baseURL: 'http://localhost:4321' },
});
// tests/navigation.spec.ts
import { expect, test } from '@playwright/test';

test('home page links to the blog', async ({ page }) => {
  await page.goto('/');
  await page.getByRole('link', { name: 'Blog' }).first().click();
  await expect(page).toHaveURL(/\/blog\/$/);
  await expect(page.getByRole('heading', { level: 1 })).toBeVisible();
});

test('unknown pages return 404', async ({ page }) => {
  const response = await page.goto('/this-page-does-not-exist/');
  expect(response?.status()).toBe(404);
});

Keep end-to-end tests few and focused on what matters: navigation, forms, the checkout or signup flow, and mobile menus. They are slower than unit tests. The Playwright tip covers running them in GitHub Actions.

These checks run against the built output and catch problems humans miss:

Check Tool What it catches
Accessibility @axe-core/playwright missing labels, alt text, ARIA misuse, contrast
Broken links linkinator or lychee internal 404s, dead external links
HTML validity html-validate duplicate ids, invalid nesting
Performance budgets Lighthouse CI regressions in LCP, CLS, page weight
Dev-time audit Astro dev toolbar accessibility and performance hints in the browser

An accessibility test with axe inside Playwright:

// tests/a11y.spec.ts
import AxeBuilder from '@axe-core/playwright';
import { expect, test } from '@playwright/test';

for (const path of ['/', '/blog/', '/contact/']) {
  test(`no serious a11y violations on ${path}`, async ({ page }) => {
    await page.goto(path);
    const results = await new AxeBuilder({ page }).analyze();
    const serious = results.violations.filter((v) => ['serious', 'critical'].includes(v.impact ?? ''));
    expect(serious).toEqual([]);
  });
}

A link check over dist/ after the build:

npx linkinator ./dist --recurse --skip "^https?://"

Automated tools find only part of accessibility issues, so pair them with keyboard testing; the Astro accessibility checklist lists the manual checks. For performance budgets, the Lighthouse CI tip has a ready config.

Testing server features

If your site renders on demand, test endpoints and actions like any HTTP API. With the Container API you can render an endpoint directly:

// src/pages/api/health.test.ts
import { experimental_AstroContainer as AstroContainer } from 'astro/container';
import { expect, test } from 'vitest';
import * as endpoint from './health';

test('health endpoint returns ok', async () => {
  const container = await AstroContainer.create();
  const response = await container.renderToResponse(endpoint, { routeType: 'endpoint' });
  expect(response.status).toBe(200);
});

For middleware and actions, Playwright against astro preview with your adapter is usually simpler and closer to production.

How much testing does an Astro site need

A practical baseline for most projects:

  1. Every site: astro check in the build, a content schema, and a link check.
  2. Sites with helpers or data logic: Vitest unit tests for those functions.
  3. Component libraries or themes: Container API tests for tricky component states.
  4. Sites with forms, auth or checkout: a handful of Playwright tests for those flows, plus axe checks on key templates.

Run them all in CI on every pull request. The GitHub Actions workflows guide shows a pipeline. If you start from one of the Komal Astro themes, the same setup applies, since each is a standard Astro project; the installation docs cover the local setup. The official Astro testing guide lists further tools, including Cypress and Storybook.

FAQ

How do I test Astro components?

Use Vitest with Astro’s Container API. Create a container with experimental_AstroContainer.create(), call renderToString(Component, { props, slots }), and assert on the returned HTML. Configure Vitest with getViteConfig() from astro/config so imports resolve like in your site.

Does Astro work with Vitest?

Yes. Astro and Vitest both run on Vite, and getViteConfig() from astro/config gives Vitest your project’s Vite configuration, including aliases and integrations. Plain TypeScript helpers can be tested without any special setup.

Should I use Playwright or Cypress with Astro?

Both work, because they test the built site in a browser. Playwright runs Chromium, Firefox and WebKit, and has a webServer option that can build and preview your site before tests start.

What is astro check?

It’s an Astro CLI command, provided by the @astrojs/check package, that type-checks the whole project, including .astro files. It reports the same errors the VS Code extension shows, so it’s ideal for CI.

Is the Astro Container API stable?

It’s still exported as experimental_AstroContainer in Astro 7, so its API may change between releases. It is widely used for component tests anyway; pin your Astro version and read release notes when upgrading.