Skip to content

测试

测试可以帮助你编写和维护有效的 Astro 代码。Astro 支持许多流行的单元测试、组件测试和端到端测试工具,包括 Jest、Mocha、Jasmine、CypressPlaywright。你甚至可以安装特定于框架的测试库(例如 React 测试库)来测试你的 UI 框架组件。

¥Testing helps you write and maintain working Astro code. Astro supports many popular tools for unit tests, component tests, and end-to-end tests including Jest, Mocha, Jasmine, Cypress and Playwright. You can even install framework-specific testing libraries such as React Testing Library to test your UI framework components.

测试框架允许你声明关于代码在特定情况下应如何表现的断言或期望,然后将它们与当前代码的实际行为进行比较。

¥Testing frameworks allow you to state assertions or expectations about how your code should behave in specific situations, then compare these to the actual behavior of your current code.

¥Unit and integration tests

一个由 esbuild 提供支持的 Vite 原生单元测试框架,支持 ESM、TypeScript 和 JSX。

¥A Vite-native unit test framework with ESM, TypeScript and JSX support powered by esbuild.

vitest.config.ts configuration file 中使用 Astro 的 getViteConfig() 辅助程序根据 Astro 项目的设置来设置 Vitest:

¥Use Astro’s getViteConfig() helper in your vitest.config.ts configuration file to set up Vitest with your Astro project’s settings:

vitest.config.ts
/// <reference types="vitest" />
import { getViteConfig } from 'astro/config';
export default getViteConfig({
test: {
// Vitest configuration options
},
});

默认情况下,getViteConfig() 将尝试在你的项目中加载 Astro 配置文件并将其应用于测试环境。从 Astro 4.8 开始,如果你需要自定义测试中应用的 Astro 配置,请将第二个参数传递给 getViteConfig()

¥By default, getViteConfig() will try to load an Astro config file in your project and apply it to the test environment. As of Astro 4.8, if you need to customize the Astro configuration applied in your tests, pass a second argument to getViteConfig():

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

请参阅 GitHub 上的 Astro + Vitest 入门模板

¥See the Astro + Vitest starter template on GitHub.

¥Vitest and Container API

Added in: astro@4.9.0

你可以使用 容器 API 本地测试 Astro 组件。首先,设置 vitest 如上所述,然后创建一个 .test.js 文件来测试你的组件:

¥You can natively test Astro components using the container API. First, setup vitest as explained above, then create a .test.js file to test your component:

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');
});

¥End-to-end tests

Playwright 是现代 Web 应用的端到端测试框架。使用 JavaScript 或 TypeScript 中的 Playwright API 在所有现代渲染引擎(包括 Chromium、WebKit 和 Firefox)上测试你的 Astro 代码。

¥Playwright is an end-to-end testing framework for modern web apps. Use the Playwright API in JavaScript or TypeScript to test your Astro code on all modern rendering engines including Chromium, WebKit, and Firefox.

¥Installation

你可以使用 VS Code 扩展 开始并运行测试。

¥You can get started and run your tests using the VS Code Extension.

或者,你可以使用你选择的包管理器在你的 Astro 项目中安装 Playwright。按照 CLI 步骤选择 JavaScript/TypeScript,命名你的测试文件夹,并添加可选的 GitHub Actions 工作流。

¥Alternatively, you can install Playwright within your Astro project using the package manager of your choice. Follow the CLI steps to choose JavaScript/TypeScript, name your test folder, and add an optional GitHub Actions workflow.

Terminal window
npm init playwright@latest

创建你的第一个 Playwright 测试

Section titled 创建你的第一个 Playwright 测试

¥Create your first Playwright test

  1. Choose a page to test. This example will test the example page index.astro below.

    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 island architecture." />
    </head>
    <body></body>
    </html>
  2. Create a new folder and add the following test file in src/test. Copy and paste the following test into the file to verify that the page meta information is correct. Update the value of the page <title> to match the page you are testing.

    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!');
    });

¥Running your Playwright tests

你可以运行单个测试或同时运行多个测试,测试一个或多个浏览器。默认情况下,你的测试结果将显示在终端中。或者,你可以打开 HTML 测试报告器以显示完整的报告并过滤测试结果。

¥You can run a single test or several tests at once, testing one or multiple browsers. By default, your test results will be shown in the terminal. Optionally, you can open the HTML Test Reporter to show a full report and filter test results.

  1. To run our test from the previous example using the command line, use the test command. Optionally, include the file name to run just the single test:

    Terminal window
    npx playwright test index.spec.ts
  2. To see the full HTML Test Report, open it using the following command:

    Terminal window
    npx playwright show-report
高级:在测试期间启动开发 Web 服务器
Section titled 高级:在测试期间启动开发 Web 服务器

¥Advanced: Launching a development web server during the tests

你还可以在运行测试脚本时使用 Playwright 配置文件中的 webServer 选项让 Playwright 启动服务器。

¥You can also have Playwright start your server when you run your testing script by using the webServer option in the Playwright configuration file.

以下是使用 npm 时所需的配置和命令的示例:

¥Here is an example of the configuration and commands required when using npm:

  1. Add a test script to your package.json file in the project root, such as "test:e2e": "playwright test".

  2. In playwright.config.ts, add the webServer object and update the command value to npm run preview.

    playwright.config.ts
    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/',
    },
    });
  3. Run npm run build, then run npm run test:e2e to run the Playwright tests.

有关 Playwright 的更多信息可以在以下链接中找到:

¥More information about Playwright can be found in the links below:

Cypress 是一款专为现代网络构建的前端测试工具。Cypress 使你能够为 Astro 站点编写端到端测试。

¥Cypress is a front-end testing tool built for the modern web. Cypress enables you to write end-to-end tests for your Astro site.

¥Installation

你可以使用你选择的包管理器安装 Cypress。

¥You can install Cypress using the package manager of your choice.

Terminal window
npm install -D cypress

This will install Cypress locally as a dev dependency for your project.

¥Configuration

在项目的根目录中,创建一个包含以下内容的 cypress.config.js 文件:

¥In the root of your project, create a cypress.config.js file with the following content:

cypress.config.js
import { defineConfig } from 'cypress'
export default defineConfig({
e2e: {
supportFile: false
}
})

创建你的第一个 Cypress 测试

Section titled 创建你的第一个 Cypress 测试

¥Create your first Cypress test

  1. Choose a page to test. This example will test the example page index.astro below.

    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 island architecture." />
    </head>
    <body>
    <h1>Hello world from Astro</h1>
    </body>
    </html>
  2. Create an index.cy.js file in the cypress/e2e folder. Use the following test in the file to verify that the page title and header are correct.

    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');
    });

¥Running your Cypress tests

Cypress 可以从命令行或 Cypress 应用运行。该应用提供了用于运行和调试测试的可视化界面。

¥Cypress can be run from the command line or from the Cypress App. The App provides a visual interface for running and debugging your tests.

首先,启动开发服务器,以便 Cypress 可以访问你的实时站点。

¥First, start the dev server so Cypress can access your live site.

要使用命令行运行上一个示例中的测试,请执行以下命令:

¥To run our test from the previous example using the command line, execute the following command:

Terminal window
npx cypress run

或者,要使用 Cypress 应用运行测试,请执行以下命令:

¥Alternatively, to run the test using the Cypress App, execute the following command:

Terminal window
npx cypress open

启动 Cypress App 后,选择 E2E 测试,然后选择要用于运行测试的浏览器。

¥Once the Cypress App is launched, choose E2E Testing, then select the browser to be used to run tests.

测试运行完成后,你应该在输出中看到绿色复选标记,确认你的测试已通过:

¥Once the test run is finished, you should see green check marks in the output confirming that your test passed:

Output from npx cypress run
Running: index.cy.js (1 of 1)
titles are correct (107ms)
1 passing (1s)

¥Next steps

有关 Cypress 的更多信息,请参见以下链接:

¥More information about Cypress can be found in the links below:

Nightwatch.js 是一个测试自动化框架,具有一套强大的工具,可用于在 Web 上编写、运行和调试测试,内置支持所有主流浏览器及其移动版本以及原生移动应用。

¥Nightwatch.js is a test automation framework with a powerful set of tools to write, run, and debug your tests across the web with built-in support for all major browsers and their mobile equivalents, as well as native mobile applications.

¥Installation

你可以使用你选择的包管理器在你的 Astro 项目中安装 NightwatchJS。按照 CLI 步骤选择 JavaScript/TypeScript,命名你的测试文件夹,并选择是否包括组件测试和移动浏览器上的测试。

¥You can install NightwatchJS within your Astro project using the package manager of your choice. Follow the CLI steps to choose JavaScript/TypeScript, name your test folder, and select whether or not to include component testing and testing on mobile browsers.

Terminal window
npm init nightwatch@latest

创建你的第一个 Nightwatch 测试

Section titled 创建你的第一个 Nightwatch 测试

¥Create your first Nightwatch test

  1. Choose a page to test. This example will test the example page index.astro below.

    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 island architecture." />
    </head>
    <body></body>
    </html>
  2. Create a new folder src/test/ and add the following test file:

    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());
    });

¥Running your NightwatchJS tests

你可以运行单个测试或同时运行多个测试,测试一个或多个浏览器。默认情况下,你的测试结果将显示在终端中。或者,你可以打开 HTML 测试报告器以显示完整的报告并过滤测试结果。

¥You can run a single test or several tests at once, testing one or multiple browsers. By default, your test results will be shown in the terminal. Optionally, you can open the HTML Test Reporter to show a full report and filter test results.

你可以使用 NightwatchJS VSCode 扩展 或使用以下 CLI 步骤运行测试:

¥You can run the tests with the NightwatchJS VSCode Extension or using the CLI steps below:

  1. To run all tests, enter the following command in the terminal. Optionally, include the file name to run just the single test:

    Terminal window
    npx nightwatch test/index.js

    Additionally, you can run the tests against a specific browser using the --environment or -e CLI argument. If you don’t have the relevant browser installed, Nightwatch will attempt to set it up for you using Selenium Manager:

    Terminal window
    npx nightwatch test/index.ts -e firefox
  2. To see the full HTML Test Report, open it using the following command:

    Terminal window
    npx nightwatch test/index.ts --open

有关 NightwatchJS 的更多信息,请参见以下链接:

¥More information about NightwatchJS can be found in the links below:

Astro 中文网 - 粤ICP备13048890号