测试
Nuxt 通过 @nuxt/test-utils 为 Nuxt 应用的端到端测试和单元测试提供了一流的支持。@nuxt/test-utils 是一个测试工具库和配置集合,目前驱动着我们用于 Nuxt 自身测试以及整个模块生态系统中的测试。
安装
为了让你能够管理其他测试依赖项,@nuxt/test-utils 提供了一些可选的对等依赖项(peer dependencies)。例如
- 你可以在
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/module添加到你的nuxt.config文件中(可选)。它会为你的 Nuxt DevTools 添加一个 Vitest 集成,支持在开发过程中运行单元测试。export default defineNuxtConfig({ modules: [ '@nuxt/test-utils/module', ], }) - 创建一个包含以下内容的
vitest.config.tsimport { defineConfig } from 'vitest/config' import { defineVitestProject } from '@nuxt/test-utils/config' export default defineConfig({ test: { projects: [ { test: { name: 'unit', include: ['test/unit/*.{test,spec}.ts'], environment: 'node', }, }, { test: { name: 'e2e', include: ['test/e2e/*.{test,spec}.ts'], environment: 'node', }, }, await defineVitestProject({ test: { name: 'nuxt', include: ['test/nuxt/*.{test,spec}.ts'], environment: 'nuxt', }, }), ], }, }) - 如果你的 Nuxt 环境测试位于
test/nuxt/之外,请参阅测试中的 TypeScript 支持以将它们添加到 TypeScript 上下文中。
@nuxt/test-utils 时,必须在你的 package.json 中指定 "type": "module",或者正确重命名你的 vitest 配置文件。即
vitest.config.m{ts,js}。
.env.test 文件来设置测试的环境变量。使用 Nuxt 运行时环境
通过使用 Vitest 项目,你可以精细控制哪些测试在哪个环境中运行
- 单元测试:将常规单元测试放在
test/unit/中 - 为了速度,这些测试将在 Node 环境中运行 - Nuxt 测试:将依赖于 Nuxt 运行时环境的测试放在
test/nuxt/中 - 这些测试将在 Nuxt 运行时环境中运行
替代方案:简单设置
如果你更喜欢简单的设置,并希望所有测试都在 Nuxt 环境中运行,你可以使用基础配置
import { defineVitestConfig } from '@nuxt/test-utils/config'
import { fileURLToPath } from 'node:url'
export default defineVitestConfig({
test: {
environment: 'nuxt',
// you can optionally set Nuxt-specific environment options
// environmentOptions: {
// nuxt: {
// rootDir: fileURLToPath(new URL('./playground', import.meta.url)),
// domEnvironment: 'happy-dom', // 'happy-dom' (default) or 'jsdom'
// overrides: {
// // other Nuxt config you want to pass
// }
// }
// }
},
})
如果你默认使用带有 environment: 'nuxt' 的简单设置,你可以根据需要在每个测试文件中选择退出 Nuxt 环境。
// @vitest-environment node
import { test } from 'vitest'
test('my test', () => {
// ... test without Nuxt environment!
})
nuxtApp 未初始化。这可能会导致难以调试的错误。组织你的测试
在基于项目的设置中,你可以按照以下方式组织测试
test/
├── e2e/
│ └── ssr.test.ts
├── nuxt/
│ ├── components.test.ts
│ └── composables.test.ts
├── unit/
│ └── utils.test.ts
你当然可以选择任何测试结构,但将 Nuxt 运行时环境与 Nuxt 端到端测试分开对于测试稳定性非常重要。
测试中的 TypeScript 支持
默认情况下,test/nuxt/ 和 tests/nuxt/ 目录中的测试文件包含在 Nuxt 应用 TypeScript 上下文中。这意味着它们将识别 Nuxt 别名(如 ~/、@/、#imports),并且 TypeScript 将知晓在你的 Nuxt 应用中工作的自动导入。
test/unit/)中的单元测试。添加其他测试目录
如果你在其他目录中有要在 Nuxt Vitest 环境中运行的测试,你可以将它们添加到配置中,从而将它们包含在 Nuxt 应用的 TypeScript 上下文中
export default defineNuxtConfig({
typescript: {
tsConfig: {
include: [
// this path is relative to the generated .nuxt/tsconfig.json
'../test/other-nuxt-context/**/*',
],
},
},
})
~/utils/helpers)时才添加 TypeScript 路径别名支持,而不是为了 Nuxt 特定的功能。运行测试
使用项目设置,你可以运行不同的测试套件
# Run all tests
npx vitest
# Run only unit tests
npx vitest --project unit
# Run only Nuxt tests
npx vitest --project nuxt
# Run tests in watch mode
npx vitest --watch
happy-dom 或 jsdom 环境中运行。在测试运行之前,将初始化一个全局 Nuxt 应用(例如,包括运行你在 app.vue 中定义的任何插件或代码)。这意味着你应特别注意不要在测试中修改全局状态(或者如果需要修改,请在事后重置它)。🎭 内置模拟(Mocks)
@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,
},
},
},
},
})
🛠️ 辅助函数(Helpers)
@nuxt/test-utils 提供了许多辅助函数,使测试 Nuxt 应用更加容易。
mountSuspended
mountSuspended 允许你在 Nuxt 环境中挂载任何 Vue 组件,支持异步设置并访问来自 Nuxt 插件的注入。
mountSuspended 包装了来自 @vue/test-utils 的 mount,因此你可以查看 Vue Test Utils 文档 以了解有关你可以传入的选项以及如何使用此工具的更多信息。例如
// @noErrors
import { expect, it } from 'vitest'
import type { Component } from 'vue'
declare module '#components' {
export const SomeComponent: Component
}
// ---cut---
// tests/components/SomeComponents.nuxt.spec.ts
import { mountSuspended } from '@nuxt/test-utils/runtime'
import { SomeComponent } from '#components'
it('can mount some component', async () => {
const component = await mountSuspended(SomeComponent)
expect(component.text()).toMatchInlineSnapshot(
'"This is an auto-imported component"',
)
})
// @noErrors
import { expect, it } from 'vitest'
// ---cut---
// tests/components/SomeComponents.nuxt.spec.ts
import { mountSuspended } from '@nuxt/test-utils/runtime'
import App from '~/app.vue'
// tests/App.nuxt.spec.ts
it('can also mount an app', async () => {
const component = await mountSuspended(App, { route: '/test' })
expect(component.html()).toMatchInlineSnapshot(`
"<div>This is an auto-imported component</div>
<div> I am a global component </div>
<div>/</div>
<a href="/test"> Test link </a>"
`)
})
选项对象接受 @vue/test-utils 的挂载选项以及以下属性
route:初始路由,或为false以跳过初始路由更改(默认值为/)。
renderSuspended
renderSuspended 允许你使用 @testing-library/vue 在 Nuxt 环境中渲染任何 Vue 组件,支持异步设置并访问来自 Nuxt 插件的注入。
这应与 Testing Library 的实用工具(例如 screen 和 fireEvent)结合使用。在你的项目中安装 @testing-library/vue 以使用它们。
此外,Testing Library 还依赖于测试全局变量来进行清理。你应该在 Vitest 配置中开启它们。
传入的组件将被渲染到 <div id="test-wrapper"></div> 中。
示例
// @noErrors
import { expect, it } from 'vitest'
import type { Component } from 'vue'
declare module '#components' {
export const SomeComponent: Component
}
// ---cut---
// tests/components/SomeComponents.nuxt.spec.ts
import { renderSuspended } from '@nuxt/test-utils/runtime'
import { SomeComponent } from '#components'
import { screen } from '@testing-library/vue'
it('can render some component', async () => {
await renderSuspended(SomeComponent)
expect(screen.getByText('This is an auto-imported component')).toBeDefined()
})
// @noErrors
import { expect, it } from 'vitest'
// ---cut---
// tests/App.nuxt.spec.ts
import { renderSuspended } from '@nuxt/test-utils/runtime'
import App from '~/app.vue'
it('can also render an app', async () => {
const html = await renderSuspended(App, { route: '/test' })
expect(html).toMatchInlineSnapshot(`
"<div id="test-wrapper">
<div>This is an auto-imported component</div>
<div> I am a global component </div>
<div>Index page</div><a href="/test"> Test link </a>
</div>"
`)
})
选项对象接受 @testing-library/vue 的渲染选项以及以下属性
route:初始路由,或为false以跳过初始路由更改(默认值为/)。
mockNuxtImport
mockNuxtImport 允许你模拟 Nuxt 的自动导入功能。例如,若要模拟 useState,你可以这样做
import { mockNuxtImport } from '@nuxt/test-utils/runtime'
mockNuxtImport('useState', () => {
return () => {
return { value: 'mocked storage' }
}
})
// your tests here
你可以显式地为模拟指定类型以确保类型安全,并在模拟复杂功能时使用传递给工厂函数的原始实现。
import { mockNuxtImport } from '@nuxt/test-utils/runtime'
mockNuxtImport<typeof useState>('useState', (original) => {
return (...args) => {
return { ...original('some-key'), value: 'mocked state' }
}
})
// or specify the target to mock
mockNuxtImport(useState, (original) => {
return (...args) => {
return { ...original('some-key'), value: 'mocked state' }
}
})
// your tests here
mockNuxtImport。它实际上是一个宏,会被转换为 vi.mock,并且 vi.mock 会被提升(hoisted),正如 Vitest 文档中所述。如果你需要模拟一个 Nuxt 导入并在不同测试之间提供不同的实现,可以通过使用 vi.hoisted 创建并导出你的模拟,然后在 mockNuxtImport 中使用这些模拟。这样你就可以访问被模拟的导入,并能在不同测试之间更改实现。请务必在每个测试之前或之后恢复模拟,以撤销运行之间的模拟状态更改。
import { vi } from 'vitest'
import { mockNuxtImport } from '@nuxt/test-utils/runtime'
const { useStateMock } = vi.hoisted(() => {
return {
useStateMock: vi.fn(() => {
return { value: 'mocked storage' }
}),
}
})
mockNuxtImport('useState', () => {
return useStateMock
})
// Then, inside a test
useStateMock.mockImplementation(() => {
return { value: 'something else' }
})
如果你只需要在某个测试内部模拟行为,也可以使用以下方法。
import { beforeEach, vi } from 'vitest'
import { mockNuxtImport } from '@nuxt/test-utils/runtime'
mockNuxtImport(useRoute, original => vi.fn(original))
beforeEach(() => {
vi.resetAllMocks()
})
// Then, inside a test
const useRouteOriginal = vi.mocked(useRoute).getMockImplementation()!
vi.mocked(useRoute).mockImplementation(
(...args) => ({ ...useRouteOriginal(...args), path: '/mocked' }),
)
mockComponent
mockComponent 允许你模拟 Nuxt 的组件。第一个参数可以是 PascalCase 格式的组件名称,或者是组件的相对路径。第二个参数是返回被模拟组件的工厂函数。
例如,要模拟 MyComponent,你可以
import { mockComponent } from '@nuxt/test-utils/runtime'
mockComponent('MyComponent', {
props: {
value: String,
},
setup (props) {
// ...
},
})
// relative path or alias also works
mockComponent('~/components/my-component.vue', () => {
// or a factory function
return defineComponent({
setup (props) {
// ...
},
})
})
// or you can use SFC for redirecting to a mock component
mockComponent('MyComponent', () => import('./MockComponent.vue'))
// your tests here
注意:你不能在工厂函数中引用局部变量,因为它们会被提升。如果你需要访问 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: 'test-field',
}))
默认情况下,你的请求将使用 GET 方法发送。你可以通过将第二个参数设置为一个对象而不是函数来使用其他方法。
import { registerEndpoint } from '@nuxt/test-utils/runtime'
registerEndpoint('/test/', {
method: 'POST',
handler: () => ({ test: 'test-field' }),
})
该对象接受以下属性
handler:事件处理函数method:(可选)要匹配的 HTTP 方法(例如 'GET'、'POST')once:(可选)如果为 true,则该处理程序将仅用于第一个匹配的请求,然后自动移除
注意:如果组件中的请求发往外部 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('useState', () => {
return () => {
return { value: 'mocked storage' }
}
})
app.e2e.spec.ts
import { $fetch, setup } from '@nuxt/test-utils/e2e'
await setup({
setupTimeout: 10000,
})
// ...
使用 @vue/test-utils
如果你更喜欢在 Nuxt 中单独使用 @vue/test-utils 进行单元测试,并且你只测试不依赖于 Nuxt 组合式函数、自动导入或上下文的组件,你可以按照以下步骤进行设置。
- 安装所需的依赖项
npm i --save-dev vitest @vue/test-utils happy-dom @vitejs/plugin-vueyarn add --dev vitest @vue/test-utils happy-dom @vitejs/plugin-vuepnpm add -D vitest @vue/test-utils happy-dom @vitejs/plugin-vuebun add --dev vitest @vue/test-utils happy-dom @vitejs/plugin-vue - 创建一个包含以下内容的
vitest.config.tsimport { 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>组件app/components/HelloWorld.vue,内容如下<template> <p>Hello world</p> </template> - 为这个新创建的组件创建一个简单的单元测试
~/components/HelloWorld.spec.tsimport { describe, expect, it } from 'vitest' import { mount } from '@vue/test-utils' import HelloWorld from './HelloWorld.vue' describe('HelloWorld', () => { it('component renders Hello world properly', () => { const wrapper = mount(HelloWorld) expect(wrapper.text()).toContain('Hello world') }) }) - 运行 vitest 命令
npm run testyarn testpnpm run testbun run test
恭喜,你已经准备好在 Nuxt 中使用 @vue/test-utils 开始单元测试了!祝测试愉快!
端到端测试
对于端到端测试,我们支持 Vitest、Jest、Cucumber 和 Playwright 作为测试运行器。
设置
在每一个利用了 @nuxt/test-utils/e2e 辅助方法的 describe 块中,你都需要在开始前设置测试上下文。
import { describe, test } from 'vitest'
import { $fetch, setup } from '@nuxt/test-utils/e2e'
describe('My test', async () => {
await setup({
// test context options
})
test('my test', () => {
// ...
})
})
在幕后,setup 会在 beforeAll、beforeEach、afterEach 和 afterAll 中执行多项任务,以正确设置 Nuxt 测试环境。
请为 setup 方法使用以下选项。
Nuxt 配置
rootDir:要进行测试的包含 Nuxt 应用的目录路径。- 类型:
string - 默认值:
'.'
- 类型:
configFile:配置文件名称。- 类型:
string - 默认值:
'nuxt.config'
- 类型:
时间设置
setupTimeout:允许setupTest完成其工作的时间(以毫秒为单位)(根据传递的选项,这可能包括构建或为 Nuxt 应用生成文件)。- 类型:
number - 默认值:
120000,在 Windows 上为240000
- 类型:
teardownTimeout:允许拆除测试环境(例如关闭浏览器)的时间(以毫秒为单位)。- 类型:
number - 默认值:
30000
- 类型:
功能
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- 类型:具有以下属性的
objecttype:要启动的浏览器类型 - 可以是chromium、firefox或webkitlaunch:在启动浏览器时将传递给 playwright 的选项object。请参阅完整 API 参考。
- 类型:具有以下属性的
runner:指定测试套件的运行器。目前推荐使用 Vitest。- 类型:
'vitest' | 'jest' | 'cucumber' - 默认值:
'vitest'
- 类型:
目标 host 端到端示例
端到端测试的一个常见用例是针对在通常用于生产环境的相同环境中运行的已部署应用进行测试。
对于本地开发或自动化部署流水线,针对单独的本地服务器进行测试可能更有效率,通常也比让测试框架在每次测试之间重新构建更快。
要为端到端测试使用单独的目标主机,只需为 setup 函数的 host 属性提供所需的 URL。
import { createPage, setup } from '@nuxt/test-utils/e2e'
import { describe, expect, it } from 'vitest'
describe('login page', async () => {
await setup({
host: 'https://:8787',
})
it('displays the email and password fields', 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')
// 'https://: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')
// you can access all the Playwright APIs from the `page` variable
使用 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
deno add --dev npm:@playwright/test npm:@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('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('test', async ({ page, goto }) => {
await goto('/', { waitUntil: 'hydration' })
await expect(page.getByRole('heading')).toHaveText('Welcome to Playwright!')
})