测试你的模块

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

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

编写单元测试

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

查看此 RFC 以加入讨论.

编写 E2E 测试

Nuxt Test Utils 是帮助你进行端到端测试的首选库。以下是推荐使用的工作流程:

  1. test/fixtures/* 内部创建一个用作“测试夹具(fixture)”的 Nuxt 应用程序
  2. 在你的测试文件中通过此夹具设置 Nuxt
  3. 使用来自 @nuxt/test-utils 的工具与该夹具进行交互(例如获取页面)
  4. 执行与此夹具相关的检查(例如“HTML 包含……”)
  5. 重复

在实践中,夹具为

test/fixtures/ssr/nuxt.config.ts
// 1. Create a Nuxt application to be used as a "fixture"
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. Setup Nuxt with this fixture inside your test file
  await setup({
    rootDir: fileURLToPath(new URL('./fixtures/ssr', import.meta.url)),
  })

  it('renders the index page', async () => {
    // 3. Interact with the fixture using utilities from `@nuxt/test-utils`
    const html = await $fetch('/')

    // 4. Perform checks related to this fixture
    expect(html).toContain('<div>ssr</div>')
  })
})

// 5. Repeat
describe('csr', async () => { /* ... */ })
这种工作流程的一个示例可以在 模块起步模板 中找到。

手动测试

在开发 Nuxt 模块时,拥有一个用于测试模块的演练场(playground)应用程序非常有用。模块起步模板内置了一个用于此目的的演练场

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

之后,你就可以像在任何常规项目中一样引用 my-module 了。