---
title: "测试你的模块"
description: "学习如何通过单元测试、集成测试和端到端测试来测试你的 Nuxt 模块。"
canonical_url: "https://nuxt.zhcndoc.com/docs/4.x/guide/modules/testing"
---
# 测试你的模块

> 学习如何通过单元测试、集成测试和端到端测试来测试你的 Nuxt 模块。

测试有助于确保你的模块在各种设置下按预期工作。在本节中，你将了解到如何对你的模块执行各种类型的测试。

## 编写单元测试

::tip
我们仍在讨论和探索如何简化 Nuxt 模块的单元测试和集成测试。
  
   

[查看此 RFC 参与讨论](https://github.com/nuxt/nuxt/discussions/18399)。
::

## 编写端到端测试（E2E）

[Nuxt Test Utils](https://nuxt.zhcndoc.com/docs/4.x/getting-started/testing) 是帮助你以端到端方式测试模块的首选库。以下是使用它的工作流程：

1. 在 `test/fixtures/*` 目录下创建一个 Nuxt 应用，作为测试“夹具”
2. 在测试文件中使用此夹具配置 Nuxt
3. 使用 `@nuxt/test-utils` 提供的工具与夹具交互（例如，获取页面）
4. 进行与此夹具相关的验证（例如，“HTML 包含...”）
5. 重复上述步骤

在实际操作中，夹具示例：

```ts [test/fixtures/ssr/nuxt.config.ts]
// 1. 创建一个用作“夹具”的 Nuxt 应用
import MyModule from '../../../src/module'

export default defineNuxtConfig({
  ssr: true,
  modules: [
    MyModule,
  ],
})
```

以及对应的测试示例：

```ts [test/rendering.ts]
import { describe, expect, it } from 'vitest'
import { fileURLToPath } from 'node:url'
import { $fetch, setup } from '@nuxt/test-utils/e2e'

describe('ssr', async () => {
  // 2. 在测试文件中使用此夹具配置 Nuxt
  await setup({
    rootDir: fileURLToPath(new URL('./fixtures/ssr', import.meta.url)),
  })

  it('渲染索引页', async () => {
    // 3. 使用 `@nuxt/test-utils` 提供的工具与夹具交互
    const html = await $fetch('/')

    // 4. 进行与此夹具相关的验证
    expect(html).toContain('<div>ssr</div>')
  })
})

// 5. 重复
describe('csr', async () => { /* ... */ })
```

::tip
此类工作流程的示例可见于[模块起步模板](https://github.com/nuxt/starter/blob/module/test/basic.test.ts)。
::

## 手动测试

在开发模块时，使用一个 Nuxt 应用游乐场来测试模块非常有用。[模块起步模板已集成了一个游乐场](https://nuxt.zhcndoc.com/docs/4.x/guide/modules/getting-started#develop-your-module)，用于此目的。

你也可以在本地使用其他 Nuxt 应用（不属于你的模块仓库的应用）测试你的模块。为此，你可以使用 [`npm pack`](https://docs.npmjs.com/cli/commands/npm-pack/) 命令，或相应的包管理器命令，从你的模块创建一个 tar 包。然后在测试项目中，将你的模块以 `"my-module": "file:/path/to/tarball.tgz"` 的形式添加到 `package.json` 的依赖包中。

之后，你就能像在普通项目中一样引用 `my-module` 了。


## Sitemap

See the full [sitemap](https://nuxt.zhcndoc.com/sitemap.md) for all pages.
