Skip to content

Latest commit

 

History

History
400 lines (296 loc) · 13.2 KB

testing.mdx

File metadata and controls

400 lines (296 loc) · 13.2 KB
title description i18nReady
测试
Astro 测试介绍
false

import { Steps } from '@astrojs/starlight/components'; import PackageManagerTabs from '~/components/tabs/PackageManagerTabs.astro';

测试可以帮助你编写和维护工作的 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" />
import { getViteConfig } from 'astro/config';

export default getViteConfig({
  test: {
    // Vitest 配置选项
  },
});

你可以在 GitHub 上查看 Astro + Vitest 启动模版

Cypress

Cypress 是一个专为现代 Web 开发而建的前端测试工具。Cypress 允许你为 Astro 站点编写端到端测试。

安装

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

```shell npm install -D cypress ```

这将会在你的项目中作为开发依赖项,将 Cypress 本地安装。

pnpm add cypress --save-dev
```shell yarn add cypress --dev ```

配置

在你的项目根目录下创建一个 cypress.config.js 文件,内容如下:

import { defineConfig } from 'cypress'

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

创建你的第一个 Cypress 测试

1. 选择一个页面进行测试。本例将测试下面的示例页面 `index.astro`。
```html title="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>
```
  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');
    });

    :::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,然后命名你的测试文件夹,并选择是否包含组件测试和在移动浏览器上测试。

```shell npm init nightwatch@latest ``` ```shell pnpm dlx create-nightwatch ``` ```shell yarn create nightwatch ```

创建你的第一个 Nightwatch 测试

1. 选择一个要测试的页面。此例将测试以下的 `index.astro` 示例页面。
```html title="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>
```
  1. 创建一个新的文件夹 src/test/ 并添加以下测试文件:

     ```js title="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());
     });
     ```
    

    :::tip[设置 baseUrl] 你可以在 nightwatch.conf.js 配置文件中设置 "baseURL": "http://localhost:4321" 来使用 browser.navigateTo("/") 代替 browser.navigateTo("http://localhost:4321/"),这样可以更方便地使用 URL。 :::

运行你的 NightwatchJS 测试

你可以一次运行一个单独的测试或多个测试,也测试一个或多个浏览器。默认情况下,你的测试结果将显示在终端中。你也可以选择打开 HTML 测试报告来查看完整报告并过滤测试结果。

你可以使用 NightwatchJS VSCode Extension 或以下的 CLI 步骤来运行测试:

1. 要运行所有测试,在终端中输入以下命令。你也可以选择包含文件名来只运行单个测试:
```sh
npx nightwatch test/index.js
```
此外,你可以使用 `--environment` 或 `-e` CLI 参数针对特定浏览器运行测试。如果你没有安装相关浏览器,Nightwatch 将尝试使用 [Selenium Manager](https://www.selenium.dev/blog/2022/introducing-selenium-manager/) 为你配置:

```sh
npx nightwatch test/index.ts -e firefox
```
  1. 要查看完整的 HTML 测试报告,使用以下命令打开它:

    npx nightwatch test/index.ts --open

:::tip 在你的生产代码上运行测试,以更接近你的实际、已部署的网站。 :::

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

Playwright

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

安装

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

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

```shell npm init playwright@latest ``` ```shell pnpm dlx create-playwright ``` ```shell yarn create playwright ```

创建你的第一个 Playwright 测试

1. 选择要测试的页面,我们将使用下面的 `index.astro` 页面为例。
```html title="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>
```
  1. 创建一个新文件夹并在 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[设置默认网址]

    你可以在 playwright.config.ts 配置文件中配置 "baseURL": "http://localhost:4321" 以使用 page.goto("/") 来替代 page.goto("http://localhost:4321/") 以使用更便捷的 URL。 :::

运行你的 Playwright 测试

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

1. 若要使用命令行运行上面的测试示例,请使用 `test` 命令。可以选择,包含只运行单个测试的文件名:
```sh
npx playwright test index.spec.ts
```
  1. 若要查看完整的 HTML 测试报告,请使用以下命令打开该报告:

    npx playwright show-report

:::tip 针对生产代码运行测试,以更接近于实时部署的站点。 :::

进阶:在测试期间启动开发 Web 服务器

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

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

1. 向项目根目录中的 package.json 文件添加一个测试脚本,例如 `"test:e2e": "playwright test"`。
  1. playwright.config.ts 中,添加 webServer 对象并更改命令为 yarn preview

    import type { PlaywrightTestConfig } from '@playwright/test';
    const config: PlaywrightTestConfig = {
      webServer: {
        command: 'yarn preview',
        url: 'http://localhost:4321/app/',
        timeout: 120 * 1000,
        reuseExistingServer: !process.env.CI,
      },
      use: {
        baseURL: 'http://localhost:4321/app/',
      },
    };
    export default config;
  2. 执行 yarn build,然后执行 yarn test:e2e 运行 Playwright 测试。

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

1. 向项目根目录中的 `package.json` 文件添加一个测试脚本,例如 `"test:e2e": "playwright test"`。
  1. 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/',
      },
    });
  2. 执行 npm run build,然后执行 npm run test:e2e 去运行 Playwright 测试。

以下链接有更多关于 Playwright 的资料: