为 Astro 项目配置测试

测试可以帮助你编写和维护正常工作的 Astro 代码。Astro 支持许多常用的单元测试、组件测试和端到端测试工具,包括 Jest、Mocha、Jasmine、Cypress 和 Playwright。你也可以安装框架专用测试库,例如 React Testing Library,测试 UI 框架组件。

测试框架允许你声明代码在特定情况下应当怎样表现,也就是断言或期望,然后把它们与实际行为进行比较。

单元和集成测试

Vitest

Vitest 是一个基于 esbuild、与 Vite 原生结合的单元测试框架,支持 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 配置,可以传入第二个参数:

export default getViteConfig(
  { test: { /* Vitest 配置项 */ } },
  {
    site: 'https://example.com/',
    trailingSlash: 'always',
  },
);

也可参考官方链接中的 Astro + Vitest 启动模板。

Vitest 和容器 API

容器 API 在 astro@4.9.0 加入,导入名称仍标记为实验性。可以用它在本地测试 Astro 组件。先按上文设置 Vitest,再创建 example.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 面向现代 Web 应用。可以使用其 JavaScript 或 TypeScript API,在 Chromium、WebKit、Firefox 等现代渲染引擎中测试 Astro 代码。

安装

可以通过 Playwright 的 VS Code 扩展开始编写和运行测试,也可以在 Astro 项目中用包管理器安装。按照 CLI 提示选择 JavaScript 或 TypeScript、指定测试目录,并决定是否添加 GitHub Actions 工作流。任选一种包管理器:

npm:

npm init playwright@latest

pnpm:

pnpm create playwright

Yarn:

yarn create playwright

创建第一个 Playwright 测试

  1. 选择要测试的页面。以下使用 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>
  1. 新建 src/test 文件夹,添加 index.spec.ts。将断言中的标题替换为实际页面标题:
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!');
});

示例名为“meta is correct”,实际只断言标题,没有验证描述元标签。可在 playwright.config.ts 中设置 "baseURL": "http://localhost:4321",之后使用 page.goto("/") 代替完整 URL。

运行 Playwright 测试

可以运行单个或多个测试,并选择一个或多个浏览器。默认在终端显示结果,也可以打开 HTML 报告查看详情、筛选结果。运行上述测试:

npx playwright test index.spec.ts

打开完整 HTML 报告:

npx playwright show-report

建议对构建后的生产代码运行测试,更接近实际部署的网站。若没有配置自动启动服务器,测试前需确保页面在相应端口可访问。

进阶:测试时自动启动 Web 服务器

Playwright 配置中的 webServer 选项可以让测试脚本自动启动服务器。使用 npm 的示例步骤如下:

  1. 在项目根目录的 package.json 中添加脚本,例如 "test:e2e": "playwright test"。
  2. 在 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/',
  },
});
  1. 先执行 npm run build,再执行 npm run test:e2e。

更多说明参阅 Playwright 入门指南和开发服务器文档。

Cypress

Cypress 是为现代 Web 开发设计的前端测试工具,可以为 Astro 站点编写端到端测试。

安装

用所选包管理器将 Cypress 安装为本地开发依赖,任选一种:

npm:

npm install cypress --save-dev

pnpm:

pnpm add --save-dev cypress

Yarn:

yarn add cypress --dev

配置

在项目根目录创建 cypress.config.js:

import { defineConfig } from 'cypress'

export default defineConfig({
  e2e: {
    supportFile: false
  }
})

创建第一个 Cypress 测试

  1. 选择页面,本例使用 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>
  <h1>Hello world from Astro</h1>
  </body>
</html>
  1. 在 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');
});

可在 cypress.config.js 的端到端配置中设置 "baseUrl": "http://localhost:4321",之后使用 cy.visit("/")。请注意 Cypress 的 baseUrl 与 Playwright 的 baseURL 大小写不同。

运行 Cypress 测试

Cypress 可以通过命令行或 Cypress App 运行。App 提供运行与调试测试的可视化界面。先启动网站服务,使测试能够访问页面,再执行:

npx cypress run

或者打开 Cypress App:

npx cypress open

App 启动后,选择 E2E Testing,再选择运行测试的浏览器。如果输出中出现绿色勾,表示该次测试通过。以下是原文的示例输出,耗时不是本稿实测值:

Running:  index.cy.js                                                                     (1 of 1)

✓ titles are correct (107ms)

1 passing (1s)
检查测试能否发现失败

可以修改页面的一级标题,再运行测试。原文用以下片段演示两个不同标题:

 <body>
   <h1>Hello world from Astro</h1>
   <h1>Hello from Astro</h1>
 </body>

实际验证时,应把被测试标题改为 Hello from Astro,与断言所期望的文字形成差异;不要把两个标题误当作都必须保留的最终页面。再次运行后,出现红色“x”表示测试失败。更多内容可参阅 Cypress 简介及应用测试文档。

NightwatchJS

Nightwatch.js 是测试自动化框架,提供编写、运行与调试跨页面测试的工具,内置支持主流浏览器、移动版本及原生移动应用。

安装

使用所选包管理器安装,按 CLI 提示选择 JavaScript 或 TypeScript、测试目录,以及是否包括组件测试或移动浏览器测试。任选一种:

npm:

npm init nightwatch@latest

pnpm:

pnpm create nightwatch

Yarn:

yarn create nightwatch

创建第一个 Nightwatch 测试

  1. 选择页面,本例使用 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>
  1. 新建 src/test/,添加 index.js:
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());
});

原 Astro 中文页面在 nightwatch.conf.js 提示中写作 "baseURL": "http://localhost:4321",并介绍用 browser.navigateTo("/") 简化 URL。静态核对 Nightwatch 官方配置文档后,其正式配置名是 baseUrl,别名为 base_url、launch_url、launchUrl。配置时应使用官方支持的拼写;原页面的 baseURL 不宜直接照抄。

运行 Nightwatch 测试

可以运行单个或多个测试,并选择一个或多个浏览器。默认结果显示在终端,也可以用 HTML 报告查看详情。可以使用 NightwatchJS VS Code 扩展,或通过命令行运行:

npx nightwatch test/index.js

通过 --environment 或 -e 指定浏览器;未安装相应浏览器时,Nightwatch 会尝试借助 Selenium Manager 配置:

npx nightwatch test/index.ts -e firefox

打开 HTML 报告:

npx nightwatch test/index.ts --open

上述三条命令保留了原页面的文件路径。它们分别使用 test/index.js 与 test/index.ts,而前面创建的是 src/test/index.js;实际项目中应统一测试目录、文件名与 JavaScript/TypeScript 选择,再按 Nightwatch 配置执行。建议对生产构建运行测试,以接近部署后的行为。

更多内容可查阅 Nightwatch 介绍和使用文档。

来源:Astro 文档团队及中文译者,测试,文档源码见 withastro/docs。本稿忠实整理官方中文全文,调整排版与少量措辞,并标明静态发现的示例边界及 Nightwatch 配置差异;代码语句保留原文。未安装或运行这些测试工具。许可依据为 MIT License。

版权与 MIT 许可
MIT License

Copyright (c) 2022 withastro

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the “Software”), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容