测试
Nuxt 通过 @nuxt/test-utils
提供对应用程序的端到端测试和单元测试的一流支持,这是一个测试工具库和配置集,目前用于 Nuxt 自身的测试 以及整个模块生态系统的测试。
安装
为了让你能够管理其他测试依赖,@nuxt/test-utils
附带了各种可选的 peer 依赖。例如:
- 你可以在
happy-dom
和jsdom
之间选择用于 Nuxt 运行时环境 - 你可以在
vitest
、cucumber
、jest
和playwright
之间选择端到端测试运行器 - 仅当你希望使用内置的浏览器测试工具(且不使用
@playwright/test
作为测试运行器)时,才需要playwright-core
npm i --save-dev @nuxt/test-utils vitest @vue/test-utils happy-dom playwright-core
yarn add --dev @nuxt/test-utils vitest @vue/test-utils happy-dom playwright-core
pnpm add -D @nuxt/test-utils vitest @vue/test-utils happy-dom playwright-core
bun add --dev @nuxt/test-utils vitest @vue/test-utils happy-dom playwright-core
单元测试
我们目前提供了一个用于需要 Nuxt 运行时环境的代码的单元测试环境。它目前仅支持 vitest
(尽管我们欢迎添加对其他运行时的支持)。
设置
- 为了允许你管理其他测试依赖,
@nuxt/test-utils
可以添加到你的nuxt.config
文件中(可选)。它会向 Nuxt DevTools 添加 Vitest 集成,支持在开发中运行单元测试。export default defineNuxtConfig({ modules: [ '@nuxt/test-utils/module' ] })
- 创建一个
vitest.config.ts
,包含以下内容:import { defineVitestConfig } from '@nuxt/test-utils/config' export default defineVitestConfig({ // 任何你需要的自定义 Vitest 配置 })
@nuxt/test-utils
时,需要在 package.json
中指定 "type": "module"
或适当重命名你的 vitest 配置文件。例如:
vitest.config.m{ts,js}
。
.env.test
文件设置测试环境变量。使用 Nuxt 运行时环境
默认情况下,@nuxt/test-utils
不会更改你的默认 Vitest 环境,因此你可以精细地选择启用,并将 Nuxt 测试与其他单元测试一起运行。
你可以通过在测试文件名称中添加 .nuxt.
(例如 my-file.nuxt.test.ts
或 my-file.nuxt.spec.ts
),或在测试文件中直接添加 @vitest-environment nuxt
注释来选择启用 Nuxt 环境。
// @vitest-environment nuxt
import { test } from 'vitest'
test('我的测试', () => {
// ... 在 Nuxt 环境中测试!
})
你也可以在 Vitest 配置中设置 environment: 'nuxt'
以为所有测试启用 Nuxt 环境。
// vitest.config.ts
import { fileURLToPath } from 'node:url'
import { defineVitestConfig } from '@nuxt/test-utils/config'
export default defineVitestConfig({
test: {
environment: 'nuxt',
// 你可以选择性地设置 Nuxt 特定的环境选项
// environmentOptions: {
// nuxt: {
// rootDir: fileURLToPath(new URL('./playground', import.meta.url)),
// domEnvironment: 'happy-dom', // 'happy-dom'(默认)或 'jsdom'
// overrides: {
// // 其他你想传递的 Nuxt 配置
// }
// }
// }
}
})
如果你默认设置了 environment: 'nuxt'
,你可以根据需要在每个测试文件中选择退出默认环境。
// @vitest-environment node
import { test } from 'vitest'
test('我的测试', () => {
// ... 在没有 Nuxt 环境的情况下测试!
})
happy-dom
或 jsdom
环境中运行。在测试运行之前,会初始化一个全局的 Nuxt 应用(包括例如运行你在 app.vue
中定义的任何插件或代码)。这意味着你应该特别注意不要在测试中修改全局状态(或者如果需要的话,在之后重置它)。🎭 内置模拟
@nuxt/test-utils
为 DOM 环境提供了一些内置模拟。
intersectionObserver
默认 true
,创建一个没有任何功能的虚拟类用于 IntersectionObserver API
indexedDB
默认 false
,使用 fake-indexeddb
创建 IndexedDB API 的功能模拟
这些可以在 vitest.config.ts
文件的 environmentOptions
部分配置:
import { defineVitestConfig } from '@nuxt/test-utils/config'
export default defineVitestConfig({
test: {
environmentOptions: {
nuxt: {
mock: {
intersectionObserver: true,
indexedDb: true,
}
}
}
}
})
🛠️ 辅助函数
@nuxt/test-utils
提供了许多辅助函数,使测试 Nuxt 应用更加容易。
mountSuspended
mountSuspended
允许你在 Nuxt 环境中挂载任何 Vue 组件,支持异步设置和访问来自 Nuxt 插件的注入。
例如:
// tests/components/SomeComponents.nuxt.spec.ts
import { mountSuspended } from '@nuxt/test-utils/runtime'
import { SomeComponent } from '#components'
it('可以挂载某个组件', async () => {
const component = await mountSuspended(SomeComponent)
expect(component.text()).toMatchInlineSnapshot(
'"这是一个自动导入的组件"'
)
})
// tests/components/SomeComponents.nuxt.spec.ts
import { mountSuspended } from '@nuxt/test-utils/runtime'
import App from '~/app.vue'
// tests/App.nuxt.spec.ts
it('也可以挂载应用', async () => {
const component = await mountSuspended(App, { route: '/test' })
expect(component.html()).toMatchInlineSnapshot(`
"<div>这是一个自动导入的组件</div>
<div> 我是一个全局组件 </div>
<div>/</div>
<a href="/test"> 测试链接 </a>"
`)
})
renderSuspended
renderSuspended
允许你使用 @testing-library/vue
在 Nuxt 环境中渲染任何 Vue 组件,支持异步设置和访问来自 Nuxt 插件的注入。
这应该与 Testing Library 的工具一起使用,例如 screen
和 fireEvent
。在你的项目中安装 @testing-library/vue 来使用这些。
此外,Testing Library 还依赖测试全局变量进行清理。你应该在 Vitest 配置 中启用这些。
传入的组件将被渲染在 <div id="test-wrapper"></div>
内部。
示例:
// tests/components/SomeComponents.nuxt.spec.ts
import { renderSuspended } from '@nuxt/test-utils/runtime'
import { SomeComponent } from '#components'
import { screen } from '@testing-library/vue'
it('可以渲染某个组件', async () => {
await renderSuspended(SomeComponent)
expect(screen.getByText('这是一个自动导入的组件')).toBeDefined()
})
// tests/App.nuxt.spec.ts
import { renderSuspended } from '@nuxt/test-utils/runtime'
import App from '~/app.vue'
it('也可以渲染应用', async () => {
const html = await renderSuspended(App, { route: '/test' })
expect(html).toMatchInlineSnapshot(`
"<div id="test-wrapper">
<div>这是一个自动导入的组件</div>
<div> 我是一个全局组件 </div>
<div>首页</div><a href="/test"> 测试链接 </a>
</div>"
`)
})
mockNuxtImport
mockNuxtImport
允许你模拟 Nuxt 的自动导入功能。例如,要模拟 useStorage
,你可以这样做:
import { mockNuxtImport } from '@nuxt/test-utils/runtime'
mockNuxtImport('useStorage', () => {
return () => {
return { value: '模拟的存储' }
}
})
// 你的测试在这里
如果你需要模拟 Nuxt 导入并在测试之间提供不同的实现,你可以通过使用 vi.hoisted
创建和暴露你的模拟,然后在 mockNuxtImport
中使用这些模拟。然后你可以访问被模拟的导入,并在测试之间更改实现。注意要在每个测试之前或之后 恢复模拟,以撤销运行之间的模拟状态变化。
import { vi } from 'vitest'
import { mockNuxtImport } from '@nuxt/test-utils/runtime'
const { useStorageMock } = vi.hoisted(() => {
return {
useStorageMock: vi.fn(() => {
return { value: '模拟的存储'}
})
}
})
mockNuxtImport('useStorage', () => {
return useStorageMock
})
// 然后,在测试中
useStorageMock.mockImplementation(() => {
return { value: '其他内容' }
})
mockComponent
mockComponent
允许你模拟 Nuxt 的组件。
第一个参数可以是 PascalCase 的组件名称,或组件的相对路径。
第二个参数是一个返回被模拟组件的工厂函数。
例如,要模拟 MyComponent
,你可以:
import { mockComponent } from '@nuxt/test-utils/runtime'
mockComponent('MyComponent', {
props: {
value: String
},
setup(props) {
// ...
}
})
// 相对路径或别名也可以
mockComponent('~/components/my-component.vue', async () => {
// 或者一个工厂函数
return defineComponent({
setup(props) {
// ...
}
})
})
// 或者你可以使用 SFC 重定向到一个模拟组件
mockComponent('MyComponent', () => import('./MockComponent.vue'))
// 你的测试在这里
注意:你不能在工厂函数中引用局部变量,因为它们会被提升。如果你需要访问 Vue API 或其他变量,你需要在工厂函数中导入它们。
import { mockComponent } from '@nuxt/test-utils/runtime'
mockComponent('MyComponent', async () => {
const { ref, h } = await import('vue')
return defineComponent({
setup(props) {
const counter = ref(0)
return () => h('div', null, counter.value)
}
})
})
registerEndpoint
registerEndpoint
允许你创建返回模拟数据的 Nitro 端点。如果你想测试一个向 API 发出请求以显示某些数据的组件,这会很有用。
第一个参数是端点名称(例如 /test/
)。
第二个参数是一个返回模拟数据的工厂函数。
例如,要模拟 /test/
端点,你可以这样做:
import { registerEndpoint } from '@nuxt/test-utils/runtime'
registerEndpoint('/test/', () => ({
test: '测试字段'
}))
默认情况下,你的请求将使用 GET
方法。你可以通过将对象作为第二个参数而不是函数来使用其他方法。
import { registerEndpoint } from '@nuxt/test-utils/runtime'
registerEndpoint('/test/', {
method: 'POST',
handler: () => ({ test: '测试字段' })
})
注意:如果你的组件中的请求指向外部 API,你可以使用
baseURL
,然后使用 Nuxt 环境覆盖配置($test
)使其为空,这样你所有的请求都会指向 Nitro 服务器。
与端到端测试的冲突
@nuxt/test-utils/runtime
和 @nuxt/test-utils/e2e
需要在不同的测试环境中运行,因此不能在同一个文件中使用。
如果你想同时使用 @nuxt/test-utils
的端到端和单元测试功能,你可以将测试拆分为单独的文件。然后你可以要么使用特殊的 // @vitest-environment nuxt
注释为每个文件指定测试环境,要么用 .nuxt.spec.ts
扩展名命名你的运行时单元测试文件。
app.nuxt.spec.ts
import { mockNuxtImport } from '@nuxt/test-utils/runtime'
mockNuxtImport('useStorage', () => {
return () => {
return { value: '模拟的存储' }
}
})
app.e2e.spec.ts
import { setup, $fetch } from '@nuxt/test-utils/e2e'
await setup({
setupTimeout: 10000,
})
// ...
@vue/test-utils
使用
如果你更喜欢单独使用 @vue/test-utils
在 Nuxt 中进行单元测试,并且你只测试不依赖 Nuxt 组合式函数、自动导入或上下文的组件,你可以按照以下步骤进行设置。
- 安装所需的依赖
npm i --save-dev vitest @vue/test-utils happy-dom @vitejs/plugin-vue
yarn add --dev vitest @vue/test-utils happy-dom @vitejs/plugin-vue
pnpm add -D vitest @vue/test-utils happy-dom @vitejs/plugin-vue
bun add --dev vitest @vue/test-utils happy-dom @vitejs/plugin-vue
- 创建一个
vitest.config.ts
,包含以下内容:import { defineConfig } from 'vitest/config' import vue from '@vitejs/plugin-vue' export default defineConfig({ plugins: [vue()], test: { environment: 'happy-dom', }, });
- 在你的
package.json
中添加一个新的测试命令"scripts": { "build": "nuxt build", "dev": "nuxt dev", ... "test": "vitest" },
- 创建一个简单的
<HelloWorld>
组件components/HelloWorld.vue
,包含以下内容:<template> <p>Hello world</p> </template>
- 为这个新创建的组件创建一个简单的单元测试
~/components/HelloWorld.spec.ts
import { describe, it, expect } from 'vitest' import { mount } from '@vue/test-utils' import HelloWorld from './HelloWorld.vue' describe('HelloWorld', () => { it('组件正确渲染 Hello world', () => { const wrapper = mount(HelloWorld) expect(wrapper.text()).toContain('Hello world') }) })
- 运行 vitest 命令
npm run test
yarn test
pnpm run test
bun run test
恭喜,你已经准备好在 Nuxt 中使用 @vue/test-utils
开始单元测试了!祝你测试愉快!
端到端测试
对于端到端测试,我们支持 Vitest、Jest、Cucumber 和 Playwright 作为测试运行器。
设置
在每个你利用 @nuxt/test-utils/e2e
辅助方法的 describe
块中,你需要在开始之前设置测试上下文。
import { describe, test } from 'vitest'
import { setup, $fetch } from '@nuxt/test-utils/e2e'
describe('我的测试', async () => {
await setup({
// 测试上下文选项
})
test('我的测试', () => {
// ...
})
})
在底层,setup
会在 beforeAll
、beforeEach
、afterEach
和 afterAll
中执行许多任务,以正确设置 Nuxt 测试环境。
请使用以下选项作为 setup
方法的参数。
Nuxt 配置
rootDir
:要测试的 Nuxt 应用所在目录的路径。- 类型:
string
- 默认值:
'.'
- 类型:
configFile
:配置文件的名称。- 类型:
string
- 默认值:
'nuxt.config'
- 类型:
时间设置
setupTimeout
:允许setupTest
完成其工作的时间(以毫秒为单位)(可能包括构建或生成 Nuxt 应用的文件,取决于传递的选项)。- 类型:
number
- 默认值:
60000
- 类型:
功能设置
build
:是否运行单独的构建步骤。- 类型:
boolean
- 默认值:
true
(如果browser
或server
被禁用,或者提供了host
,则为false
)
- 类型:
server
:是否启动服务器以响应测试套件中的请求。- 类型:
boolean
- 默认值:
true
(如果提供了host
,则为false
)
- 类型:
port
:如果提供,将启动的测试服务器端口设置为该值。- 类型:
number | undefined
- 默认值:
undefined
- 类型:
host
:如果提供,将用作测试目标的 URL,而不是构建和运行新服务器。用于针对应用程序的部署版本运行"真实"的端到端测试,或者针对已经运行的本地服务器(这可能会显著减少测试执行时间)非常有用。参见下面的目标主机端到端示例。- 类型:
string
- 默认值:
undefined
- 类型:
browser
:在底层,Nuxt 测试工具使用playwright
进行浏览器测试。如果设置了此选项,将启动浏览器并可以在后续测试套件中控制。- 类型:
boolean
- 默认值:
false
- 类型:
browserOptions
- 类型:具有以下属性的
object
type
:要启动的浏览器类型 -chromium
、firefox
或webkit
launch
:将在启动浏览器时传递给 playwright 的选项对象。参见 完整 API 参考。
- 类型:具有以下属性的
runner
:指定测试套件的运行器。目前推荐使用 Vitest。- 类型:
'vitest' | 'jest' | 'cucumber'
- 默认值:
'vitest'
- 类型:
目标 host
端到端示例
端到端测试的一个常见用例是针对在通常用于生产的相同环境中运行的部署应用程序运行测试。
对于本地开发或自动化部署管道,针对单独的本地服务器进行测试可能更高效,并且通常比允许测试框架在测试之间重建更快。
要利用单独的目标主机进行端到端测试,只需向 setup
函数的 host
属性提供所需的 URL。
import { setup, createPage } from '@nuxt/test-utils/e2e'
import { describe, it, expect } from 'vitest'
describe('登录页面', async () => {
await setup({
host: 'http://localhost:8787',
})
it('显示电子邮件和密码字段', async () => {
const page = await createPage('/login')
expect(await page.getByTestId('email').isVisible()).toBe(true)
expect(await page.getByTestId('password').isVisible()).toBe(true)
})
})
API
$fetch(url)
获取服务器渲染页面的 HTML。
import { $fetch } from '@nuxt/test-utils/e2e'
const html = await $fetch('/')
fetch(url)
获取服务器渲染页面的响应。
import { fetch } from '@nuxt/test-utils/e2e'
const res = await fetch('/')
const { body, headers } = res
url(path)
获取给定页面的完整 URL(包括测试服务器运行的端口)。
import { url } from '@nuxt/test-utils/e2e'
const pageUrl = url('/page')
// 'http://localhost:6840/page'
浏览器测试
我们在 @nuxt/test-utils
中提供了使用 Playwright 的内置支持,无论是通过编程方式还是通过 Playwright 测试运行器。
createPage(url)
在 vitest
、jest
或 cucumber
中,你可以使用 createPage
创建一个配置好的 Playwright 浏览器实例,并(可选地)将其指向运行服务器的路径。你可以在 Playwright 文档 中找到更多关于可用 API 方法的信息。
import { createPage } from '@nuxt/test-utils/e2e'
const page = await createPage('/page')
// 你可以从 `page` 变量访问所有 Playwright API
使用 Playwright 测试运行器
我们还提供了在 Playwright 测试运行器 中测试 Nuxt 的一流支持。
npm i --save-dev @playwright/test @nuxt/test-utils
yarn add --dev @playwright/test @nuxt/test-utils
pnpm add -D @playwright/test @nuxt/test-utils
bun add --dev @playwright/test @nuxt/test-utils
你可以提供全局 Nuxt 配置,使用与本节前面提到的 setup()
函数相同的配置细节。
import { fileURLToPath } from 'node:url'
import { defineConfig, devices } from '@playwright/test'
import type { ConfigOptions } from '@nuxt/test-utils/playwright'
export default defineConfig<ConfigOptions>({
use: {
nuxt: {
rootDir: fileURLToPath(new URL('.', import.meta.url))
}
},
// ...
})
你的测试文件应该直接从 @nuxt/test-utils/playwright
使用 expect
和 test
:
import { expect, test } from '@nuxt/test-utils/playwright'
test('测试', async ({ page, goto }) => {
await goto('/', { waitUntil: 'hydration' })
await expect(page.getByRole('heading')).toHaveText('Welcome to Playwright!')
})
你也可以在测试文件中直接配置你的 Nuxt 服务器:
import { expect, test } from '@nuxt/test-utils/playwright'
test.use({
nuxt: {
rootDir: fileURLToPath(new URL('..', import.meta.url))
}
})
test('测试', async ({ page, goto }) => {
await goto('/', { waitUntil: 'hydration' })
await expect(page.getByRole('heading')).toHaveText('Welcome to Playwright!')
})