测试
测试可以帮助你编写和维护工作的 Astro 代码。Astro 支持许多流行的单元测试、组件测试和端到端测试工具,包括 Jest、Mocha、Jasmine、Cypress 和 Playwright。你甚至可以安装特定于框架的测试库,例如 React Test Library,以测试你的 UI 框架组件。
测试框架允许你声明关于代码在特定情况下应该如何行为的 断言 (assertions) 或 期望 (expectations),然后将这些断言或期望与当前代码的实际行为进行比较。
单元和集成测试
Section titled “单元和集成测试”Vitest
Section titled “Vitest”Vitest 是一个基于 esbuild 的 Vite-native 单元测试框架,它支持 ESM、TypeScript 和 JSX。
在你的 vitest.config.ts 配置文件 中使用 getViteConfig() 辅助函数来设置 Vitest。
/// <reference types="vitest/config" />import { getViteConfig } from 'astro/config';
export default getViteConfig({ test: { // Vitest 配置选项 },});默认情况下,getViteConfig() 会尝试加载你项目中的 Astro 配置文件,并将其应用到测试环境中。
从 Astro 4.8 版本开始,如果你需要自定义在测试中应用的 Astro 配置,可以向 getViteConfig() 传递第二个参数:
export default getViteConfig( { test: { /* Vitest 配置项 */ } }, { site: 'https://example.com/', trailingSlash: 'always', },);你可以在 GitHub 上查看 Astro + Vitest 启动模版。
Vitest 和容器 API
Section titled “Vitest 和容器 API”
添加于:
astro@4.9.0
你可以使用 容器 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');});Playwright
Section titled “Playwright”Playwright 是一个针对现代网络应用的端到端测试框架。使用 JavaScript 或 TypeScript 中的 Playwright API 在所有现代渲染引擎 (包括 Chromium、WebKit 和 Firefox) 上测试 Astro 代码。
你可以使用 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="en"><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>