测试有助于确保你的模块在各种设置下都能按预期工作。 在本节中了解如何对你的模块执行各种类型的测试。
Nuxt Test Utils 是帮助你以端到端方式测试模块的首选库。 以下是与它一起采用的工作流程
test/fixtures/* 中的“fixture”(示例项目)@nuxt/test-utils 的实用程序与 fixture 交互(例如,获取一个页面)在实践中,fixture
// 1. Create a Nuxt application to be used as a "fixture"
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. 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。