🔥 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)
Deployment••By Komal Nakrani

Astro Vitest Setup for Unit and Component Tests

Set up Astro Vitest with getViteConfig so aliases and Astro config apply, unit-test utilities, and render .astro components to HTML with the Container API.

#Astro#Testing#Vitest

To run unit tests in an Astro project with Vitest, install vitest and create a vitest.config.ts that wraps your settings in getViteConfig() from astro/config. Tests then share Astro’s Vite setup, including path aliases and integrations. To test .astro components themselves, render them to an HTML string with the experimental Container API and assert on the output.

Key Takeaways

  • getViteConfig() makes Vitest load your Astro config, so imports resolve exactly as they do in the build.
  • Plain TypeScript utilities (dates, slugs, sorting) are the easiest and most valuable things to test.
  • experimental_AstroContainer from astro/container renders .astro components to strings for assertions.
  • Use Playwright for full pages in a browser; Vitest is for units and single components.

Install and configure

# Terminal
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'],
  },
});
{
  "scripts": {
    "test": "vitest",
    "test:run": "vitest run"
  }
}

vitest runs in watch mode locally; vitest run runs once, which is what you want in CI.

Test a utility

Start with the logic that decides what visitors see. A reading-time helper is a typical example:

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

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

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

The @/utils import works because getViteConfig() applies the alias from tsconfig.json. See our path aliases tip for the setup.

Render an .astro component

The Container API renders a component outside a running site:

---
// src/components/Badge.astro
interface Props {
  label: string;
  tone?: 'info' | 'warning';
}
const { label, tone = 'info' } = Astro.props;
---
<span class:list={['badge', `badge--${tone}`]}>{label}</span>
// src/components/Badge.test.ts
import { experimental_AstroContainer as AstroContainer } from 'astro/container';
import { expect, test } from 'vitest';
import Badge from './Badge.astro';

test('renders the label with the right tone class', async () => {
  const container = await AstroContainer.create();
  const html = await container.renderToString(Badge, {
    props: { label: 'Beta', tone: 'warning' },
  });

  expect(html).toContain('Beta');
  expect(html).toContain('badge--warning');
});

renderToString() also accepts slots, params and locals, so you can test components that read Astro.params or middleware data. The API is marked experimental, so pin your Astro version in CI and check the release notes on upgrades. Components that use framework islands need their renderer added to the container; the Container API guide shows how.

What not to test with Vitest

Content collection queries, routing and image optimisation depend on the full build. Test those by running astro build in CI and checking the output, or with browser tests. Our Playwright tip covers end-to-end tests, and the testing tools overview compares the options.

Run in CI

# .github/workflows/test.yml
name: test
on: [push, pull_request]
jobs:
  unit:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: '22'
      - run: npm ci
      - run: npx vitest run

Current Astro releases need Node.js 22.23.4 or newer; node-version: '22' installs the latest 22.x release. Themes in our Astro theme catalog are standard Astro projects, so this config works in them unchanged. The official testing guide has more examples.

FAQ

How do I use Vitest with Astro?

Install vitest, create vitest.config.ts that exports getViteConfig({ test: {...} }) from astro/config, and run npx vitest. Your Astro config and aliases then apply in tests.

Can Vitest test .astro components?

Yes, with the Container API. Import experimental_AstroContainer from astro/container, render the component with renderToString(), and assert on the HTML.

Why does my Astro test fail to resolve an import?

Usually the config does not use getViteConfig(), so aliases and Astro’s Vite plugins are missing. Wrap your Vitest config in it.

Should I use Vitest or Playwright for Astro?

Both, for different jobs. Vitest is fast and suits utilities and single components. Playwright runs the built site in real browsers and tests navigation, forms and islands.