测试有助于确保你的模块在各种设置下按预期工作。在本节中,你将了解到如何对你的模块执行各种类型的测试。
Nuxt 测试工具 是帮助你以端到端方式测试模块的首选库。以下是推荐的工作流程:
test/fixtures/* 目录下创建一个 Nuxt 应用,作为测试“夹具”@nuxt/test-utils 提供的工具与夹具交互(例如,获取页面)在实际操作中,夹具示例:
// 1. 创建一个用作“夹具”的 Nuxt 应用
import MyModule from '../../../src/module'
export default defineNuxtConfig({
ssr: true,
modules: [
MyModule,
],
})
以及对应的测试示例:
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 () => { /* ... */ })
在开发你的模块时,拥有一个 Nuxt 试玩应用以测试模块非常有用。模块起步模板为此集成了相关内容。
你也可以在本地使用其他 Nuxt 应用(不属于你的模块仓库的应用)测试你的模块。为此,你可以使用 npm pack 命令,或相应的包管理器命令,从你的模块创建一个 tar 包。然后在测试项目中,将你的模块以 "my-module": "file:/path/to/tarball.tgz" 的形式添加到 package.json 的依赖包中。
之后,你就能像在普通项目中一样引用 my-module 了。