测试你的模块

了解如何使用单元测试、集成测试和端到端 (E2E) 测试来测试你的 Nuxt 模块。

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

编写单元测试

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

查看此 RFC 以加入讨论.

编写 E2E 测试

Nuxt Test Utils 是帮助你以端到端方式测试模块的首选库。 以下是与它一起采用的工作流程

  1. 创建一个 Nuxt 应用程序,用作 test/fixtures/* 中的“fixture”(示例项目)
  2. 在你的测试文件中使用此 fixture 设置 Nuxt
  3. 使用来自 @nuxt/test-utils 的实用程序与 fixture 交互(例如,获取一个页面)
  4. 对该 fixture 执行检查(例如,“HTML 包含 ...”)
  5. 重复

在实践中,fixture

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 () => { /* ... */ })
此类工作流程的一个示例可以在模块启动器.

手动测试

在开发模块时,拥有一个用于测试模块的 playground Nuxt 应用程序非常有用。模块启动器为此目的集成了一个

你可以在本地使用其他 Nuxt 应用程序(不是你的模块存储库中的应用程序)来测试你的模块。 要做到这一点,你可以使用npm pack命令,或你的包管理器的等效命令,来为你的模块创建一个 tarball。 然后在你测试的项目中,你可以将你的模块作为以下形式添加到 package.json 的 packages 中: "my-module": "file:/path/to/tarball.tgz"

之后,你应该能够像在任何常规项目中一样引用 my-module