跳到主要内容

测试你的模块

学习如何对你的 Nuxt 模块进行单元、集成和 E2E 测试。

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

编写单元测试

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

查看此 RFC 以加入讨论

编写 E2E 测试

Nuxt Test Utils 是帮助你以端到端方式测试模块的必备库。下面是使用它时应采用的工作流:

  1. test/fixtures/* 内部创建一个用作「fixture」的 Nuxt 应用
  2. 在你的测试文件中用这个 fixture 设置 Nuxt
  3. 使用来自 @nuxt/test-utils 的工具函数与这个 fixture 交互(例如 fetch 一个页面)
  4. 执行与此 fixture 相关的检查(例如「HTML 包含……」)
  5. 重复

在实践中,这个 fixture 如下:

test/fixtures/ssr/nuxt.config.ts
// 1. 创建一个用作「fixture」的 Nuxt 应用
import MyModule from '../../../src/module'

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

以及它的测试:

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. 在你的测试文件中用这个 fixture 设置 Nuxt
  await setup({
    rootDir: fileURLToPath(new URL('./fixtures/ssr', import.meta.url)),
  })

  it('renders the index page', async () => {
    // 3. 使用来自 `@nuxt/test-utils` 的工具函数与这个 fixture 交互
    const html = await $fetch('/')

    // 4. 执行与此 fixture 相关的检查
    expect(html).toContain('<div>ssr</div>')
  })
})

// 5. 重复
describe('csr', async () => { /* ... */ })
此工作流的一个示例可在 模块启动模板 上查看。

手动测试

拥有一个 playground Nuxt 应用来在开发时测试你的模块非常有用。模块启动模板为此集成了一个 playground

你可以与其它 Nuxt 应用(不属于你模块仓库的应用)在本地测试你的模块。为此,你可以使用 npm pack 命令(或你包管理器的等价命令),从你的模块创建一个 tarball。然后在你的测试项目中,你可以将你的模块作为 "my-module": "file:/path/to/tarball.tgz" 添加到 package.json 的依赖中。

之后,你就能像在其它常规项目中一样引用 my-module 了。