测试
测试可以帮助你编写和维护工作的 Astro 代码。Astro 支持许多流行的单元测试、组件测试和端到端测试工具,包括 Jest、Mocha、Jasmine、Cypress 和 Playwright。你甚至可以安装特定于框架的测试库,例如 React Test Library,以测试你的 UI 框架组件。
测试框架允许你声明关于代码在特定情况下应该如何行为的 断言 (assertions) 或 期望 (expectations),然后将这些断言或期望与当前代码的实际行为进行比较。
单元和集成测试
Vitest
Vitest 是一个基于 esbuild 的 Vite-native 单元测试框架,它支持 ESM、TypeScript 和 JSX。
在你的 vitest.config.ts 配置文件 中使用 getViteConfig() 辅助函数来设置 Vitest。
// vitest.config.ts
/// <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
你可以使用 容器 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
Playwright 是一个针对现代网络应用的端到端测试框架。使用 JavaScript 或 TypeScript 中的 Playwright API 在所有现代渲染引擎 (包括 Chromium、WebKit 和 Firefox) 上测试 Astro 代码。
安装
你可以使用 VS Code 扩展 开始并运行你的测试。
或者,你可以使用你选择的包管理器在你的 Astro 项目中安装 Playwright。按照 CLI 步骤选择 JavaScript/TypeScript,命名测试文件夹,并添加一个可选的 GitHub Actions 工作流。
npm init playwright@latest
pnpm create playwright
yarn create playwright
创建你的第一个 Playwright 测试
选择要测试的页面,我们将使用下面的
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>创建一个新文件夹并在
src/test中添加以下测试文件。将下面的测试复制并粘贴到文件中,以验证页面元信息是否正确。更新页面<title>的值以匹配你正在测试的页面。import { test, expect } from '@playwright/test'; test('meta is correct', async ({ page }) => { await page.goto("http://localhost:4321/"); await expect(page).toHaveTitle('Astro is awesome!'); });:::tip[设置
baseUrl]你可以在playwright.config.ts配置文件中配置"baseURL": "http://localhost:4321"以使用page.goto("/")来替代page.goto("http://localhost:4321/")以使用更便捷的 URL。:::
运行你的 Playwright 测试
你可以同时运行单个测试或多个测试,测试一个或多个浏览器。默认情况下,你的测试结果将显示在终端中。或者,你可以打开 HTML Test Reporter 以显示完整的报告和筛选测试结果。
若要使用命令行运行上面的测试示例,请使用
test命令。可以选择,包含只运行单个测试的文件名:npx playwright test index.spec.ts若要查看完整的 HTML 测试报告,请使用以下命令打开该报告:
npx playwright show-report
:::tip针对生产代码运行测试,以更接近于实时部署的站点。:::
进阶:在测试期间启动开发 Web 服务器
当你使用 Playwright 配置文件中的 webServer 选项运行测试脚本时,你也可以让 Playwright 启动服务器。
以下是使用 npm 时所需的配置和命令示例:
向项目根目录中的 package.json 文件添加一个测试脚本,例如
"test:e2e": "playwright test"。在
playwright.config.ts中,添加webServer对象并更改命令为npm run preview。import { defineConfig } from '@playwright/test'; export default defineConfig({ webServer: { command: 'npm run preview', url: 'http://localhost:4321/', timeout: 120 * 1000, reuseExistingServer: !process.env.CI, }, use: { baseURL: 'http://localhost:4321/', }, });执行
npm run build,然后执行npm run test:e2e来运行 Playwright 测试。
关于 Playwright 的更多信息,请参考以下链接:
Cypress
Cypress 是一个专为现代 Web 开发而建的前端测试工具。Cypress 允许你为 Astro 站点编写端到端测试。
安装
你可以使用你选择的包管理器来安装 Cypress。这一步将会为你的项目在本地安装 Cypress 以作为开发依赖项。
npm install cypress --save-dev
pnpm add --save-dev cypress
yarn add cypress --dev
配置
在你的项目根目录下创建一个 cypress.config.js 文件,内容如下:
import { defineConfig } from 'cypress'
export default defineConfig({
e2e: {
supportFile: false
}
})创建你的第一个 Cypress 测试
选择一个页面进行测试。本例将测试下面的示例页面
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> <h1>Hello world from Astro</h1> </body> </html>在
cypress/e2e文件夹中创建一个名为index.cy.js的文件。在文件中使用以下测试来验证页面的标题和开头是否正确。it('titles are correct', () => { const page = cy.visit('http://localhost:4321'); page.get('title').should('have.text', 'Astro is awesome!') page.get('h1').should('have.text', 'Hello world from Astro'); });:::tip[设置一个 baseUrl]你可以在名为
cypress.config.js的配置文件中设置"baseUrl": "http://localhost:4321",以便使用cy.visit("/")而不是cy.visit("http://localhost:4321/")来使用更便捷的 URL。:::
运行你的 Cypress 测试
Cypress 可以在命令行或 Cypress App 中运行。Cypress App 提供了一个可视化界面,用于运行和调试你的测试。
首先,启动开发服务器,这样 Cypress 就可以访问你的实时网站。
要通过命令行运行我们之前示例中的测试,请执行以下命令:
npx cypress run或者,要通过 Cypress App 运行测试,请执行以下命令:
npx cypress open在 Cypress App 启动后,选择 E2E Testing,然后选择要用于运行测试的浏览器。
当测试运行完成时,如果你在输出中看到一个绿色的勾,这证明你的测试通过了:
Running: index.cy.js (1 of 1)
✓ titles are correct (107ms)
1 passing (1s):::note[测试失败]为了确保你的测试有效,你可以修改 index.astro 文件中的以下行:
<body>
<h1>Hello world from Astro</h1>
<h1>Hello from Astro</h1>
</body>然后再次运行测试。如果你在输出中看到一个红色的 "x",这证明你的测试失败了。:::
下一步
关于 Cypress 的更多信息可以在以下链接中找到:
NightwatchJS
Nightwatch.js 是一个测试自动化框架,它配备了一套强大的工具,可以用来编写、运行和调试你的跨网页测试,内置支持所有主要浏览器及其移动端版本,以及原生移动端应用程序。
安装
你可以在你的 Astro 项目中使用你选择的包管理器安装 NightwatchJS。按照 CLI 的步骤选择 JavaScript/TypeScript,然后命名你的测试文件夹,并选择是否包含组件测试和在移动浏览器上测试。
npm init nightwatch@latest
pnpm create nightwatch
yarn create nightwatch
创建你的第一个 Nightwatch 测试
选择一个要测试的页面。此例将测试以下的
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>创建一个新的文件夹
src/test/并添加以下测试文件:describe('Astro testing with Nightwatch', function () { before(browser => browser.navigateTo('http://localhost:4321/')); it("check that the title is correct", function (browser) { browser.assert.titleEquals('Astro is awesome!') }); after(browser => browser.end()); });:::tip[设置
baseUrl]你可以在nightwatch.conf.js配置文件中设置"baseURL": "http://localhost:4321"来使用browser.navigateTo("/")代替browser.navigateTo("http://localhost:4321/"),这样可以更方便地使用 URL。:::
运行你的 NightwatchJS 测试
你可以一次运行一个单独的测试或多个测试,也测试一个或多个浏览器。默认情况下,你的测试结果将显示在终端中。你也可以选择打开 HTML 测试报告来查看完整报告并过滤测试结果。
你可以使用 NightwatchJS VSCode Extension 或以下的 CLI 步骤来运行测试:
要运行所有测试,在终端中输入以下命令。你也可以选择包含文件名来只运行单个测试:
npx nightwatch test/index.js此外,你可以使用
--environment或-eCLI 参数针对特定浏览器运行测试。如果你没有安装相关浏览器,Nightwatch 将尝试使用 Selenium Manager 为你配置:npx nightwatch test/index.ts -e firefox要查看完整的 HTML 测试报告,使用以下命令打开它:
npx nightwatch test/index.ts --open
:::tip在你的生产代码上运行测试,以更接近你的实际、已部署的网站。:::
更多关于 NightwatchJS 的信息可以在以下链接中找到:
Learn