テスト
テストは、動作するAstroコードを書き、メンテナンスするのに役立ちます。Astroは、Jest、Mocha、Jasmine、Cypress、Playwrightなど、ユニットテスト、コンポーネントテスト、E2Eテストのための多くの人気ツールをサポートしています。また、React Testing Libraryのようなフレームワーク固有のテストライブラリをインストールして、UIフレームワークコンポーネントをテストすることもできます。
テストフレームワークを使うと、特定の状況においてコードがどのように動作すべきかについてのアサーションや期待値を記述し、それを実際のコードの動作と比較できます。
ユニットテストと統合テスト
Section titled “ユニットテストと統合テスト”Vitest
Section titled “Vitest”Viteネイティブのユニットテストフレームワークで、esbuildによるESM・TypeScript・JSXサポートを備えています。
AstroのgetViteConfig()ヘルパーをvitest.config.ts設定ファイルで使用して、Astroプロジェクトの設定でVitestをセットアップします:
/// <reference types="vitest/config" />import { getViteConfig } from 'astro/config';
export default getViteConfig({ test: { // Vitestの設定オプション },});デフォルトでは、getViteConfig()はプロジェクト内のAstro設定ファイルを読み込み、テスト環境に適用しようとします。Astro 4.8以降、テストに適用されるAstro設定をカスタマイズする必要がある場合は、getViteConfig()に第2引数を渡します:
export default getViteConfig( { test: { /* Vitestの設定オプション */ } }, { site: 'https://example.com/', trailingSlash: 'always', },);GitHubのAstro + Vitestスターターテンプレートを参照してください。
VitestとContainer API
Section titled “VitestとContainer API”
追加:
astro@4.9.0
Container API (EN)を使用して、Astroコンポーネントをネイティブにテストできます。まず、上記の説明に従ってvitestをセットアップし、コンポーネントをテストするための.test.jsファイルを作成します:
import { experimental_AstroContainer as AstroContainer } from 'astro/container';import { expect, test } from 'vitest';import Card from '../src/components/Card.astro';
test('Card with slots', async () => { const container = await AstroContainer.create(); const result = await container.renderToString(Card, { slots: { default: 'Card content', }, });
expect(result).toContain('This is a card'); expect(result).toContain('Card content');});E2Eテスト
Section titled “E2Eテスト”Playwright
Section titled “Playwright”Playwrightは、モダンなWebアプリ向けのE2Eテストフレームワークです。JavaScriptまたはTypeScriptでPlaywright APIを使用して、Chromium、WebKit、Firefoxを含むすべてのモダンなレンダリングエンジンでAstroコードをテストできます。
インストール
Section titled “インストール”VS Code拡張機能を使用して、テストを行うことができます。
または、お好みのパッケージマネージャーを使用してAstroプロジェクト内にPlaywrightをインストールできます。CLIの手順に従って、JavaScript/TypeScriptを選択し、テストフォルダに名前を付け、オプションでGitHub Actionsワークフローを追加します。
npm init playwright@latestpnpm create playwrightyarn create playwright最初のPlaywrightテストを作成する
Section titled “最初のPlaywrightテストを作成する”-
テストするページを選択します。この例では、以下の
index.astroページをテストします。src/pages/index.astro ------<html lang="ja"><head><title>Astro is awesome!</title><meta name="description" content="Pull content from anywhere and serve it fast with Astro's next-gen islands architecture." /></head><body></body></html>