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

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

测试有助于确保你的模块在各种配置下按预期工作。本节将介绍如何对你的模块进行各种类型的测试。

## 编写单元测试

::tip
我们仍在讨论和探索如何简化 Nuxt 模块的单元测试和集成测试。
:br :br
[查看此 RFC 并参与讨论](https://github.com/nuxt/nuxt/discussions/18399)。
::

## 编写端到端测试

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

1. 在 `test/fixtures/*` 内创建一个 Nuxt 应用，作为“测试夹具”（fixture）
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)。
::

## 手动测试

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

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

之后，你就可以像引用常规项目依赖一样引用 `my-module` 了。


## Sitemap

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