Nuxt 通过@nuxt/test-utils 为你的 Nuxt 应用提供一流的端到端和单元测试支持,这是一个测试工具和配置库,目前支持我们在 Nuxt 本身使用的测试以及整个模块生态系统中的测试。
为了让你能够管理你的其他测试依赖,@nuxt/test-utils 附带了各种可选的对等依赖。例如
happy-dom和jsdom之间选择一个用于运行时 Nuxt 环境vitest、cucumber、jest和playwright之间选择一个用于端到端测试运行器@playwright/test作为你的测试运行器)时,才需要playwright-corenpm 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.ts文件import { defineConfig } from 'vitest/config'
import { defineVitestProject } from '@nuxt/test-utils/config'
export default defineConfig({
test: {
projects: [
{
test: {
name: 'unit',
include: ['test/{e2e,unit}/*.{test,spec}.ts'],
environment: 'node',
},
},
await defineVitestProject({
test: {
name: 'nuxt',
include: ['test/nuxt/*.{test,spec}.ts'],
environment: 'nuxt',
},
}),
],
},
})
@nuxt/test-utils时,必须在你的package.json中指定"type": "module",或者相应地重命名你的 vitest 配置文件。例如,
vitest.config.m{ts,js}。
.env.test文件来设置测试的环境变量。使用Vitest 项目,你可以对哪些测试在哪个环境中运行进行细粒度控制
test/unit/中 - 这些测试在 Node 环境中运行以提高速度test/nuxt/中 - 这些测试将在 Nuxt 运行时环境中运行如果你喜欢更简单的设置,并希望所有测试都在 Nuxt 环境中运行,你可以使用基本配置
import { defineVitestConfig } from '@nuxt/test-utils/config'
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 端到端测试分开对于测试稳定性很重要。
通过项目设置,你可以运行不同的测试套件
# 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中定义的任何插件或代码)。这意味着你应该特别注意不要在测试中改变全局状态(或者,如果需要,之后将其重置)。@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 应用程序更容易。
mountSuspendedmountSuspended允许你在 Nuxt 环境中挂载任何 Vue 组件,允许异步设置和访问 Nuxt 插件的注入。
例如
// 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"',
)
})
// 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>"
`)
})
renderSuspendedrenderSuspended允许你使用@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('can render some component', async () => {
await renderSuspended(SomeComponent)
expect(screen.getByText('This is an auto-imported component')).toBeDefined()
})
// 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>"
`)
})
mockNuxtImportmockNuxtImport允许你模拟 Nuxt 的自动导入功能。例如,要模拟useStorage,你可以这样做
import { mockNuxtImport } from '@nuxt/test-utils/runtime'
mockNuxtImport('useStorage', () => {
return () => {
return { value: 'mocked storage' }
}
})
// your tests here
中所述。如果你需要模拟 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: 'mocked storage' }
}),
}
})
mockNuxtImport('useStorage', () => {
return useStorageMock
})
// Then, inside a test
useStorageMock.mockImplementation(() => {
return { value: 'something else' }
})
mockComponentmockComponent允许你模拟 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)
},
})
})
registerEndpointregisterEndpoint允许你创建 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' }),
})
注意:如果你的组件中的请求发往外部 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: 'mocked storage' }
}
})
app.e2e.spec.ts
import { $fetch, setup } from '@nuxt/test-utils/e2e'
await setup({
setupTimeout: 10000,
})
// ...
如果你更喜欢单独使用@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>组件app/components/HelloWorld.vue,内容如下<template>
<p>Hello world</p>
</template>
~/components/HelloWorld.spec.ts创建一个简单的单元测试import { 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')
})
})
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 { $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方法。
rootDir:包含待测试 Nuxt 应用的目录路径。string'.'configFile:配置文件名。string'nuxt.config'setupTimeout:允许setupTest完成工作(可能包括为 Nuxt 应用程序构建或生成文件,具体取决于传递的选项)的时间量(以毫秒为单位)。number120000,在 Windows 上为240000teardownTimeout:允许拆除测试环境(例如关闭浏览器)的时间量(以毫秒为单位)。number30000build:是否运行单独的构建步骤。booleantrue(如果browser或server被禁用,或者提供了host,则为false)server:是否启动服务器以响应测试套件中的请求。booleantrue(如果提供了host,则为false)port:如果提供,将启动的测试服务器端口设置为该值。number | undefinedundefinedhost:如果提供,则使用此 URL 作为测试目标,而不是构建和运行新服务器。对于针对已部署应用程序的生产版本或已运行的本地服务器运行“真实”端到端测试非常有用(这可以显著缩短测试执行时间)。请参阅下面的目标主机端到端示例。stringundefinedbrowser:在底层,Nuxt 测试工具使用playwright进行浏览器测试。如果设置此选项,将启动一个浏览器,并在随后的测试套件中进行控制。booleanfalsebrowserOptionsobjecttype:要启动的浏览器类型 - 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)
})
})
$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 文档.
import { createPage } from '@nuxt/test-utils/e2e'
const page = await createPage('/page')
// you can access all the Playwright APIs from the `page` variable
使用 Playwright 测试运行器进行测试我们还为在.
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
Playwright 测试运行器
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和testimport { 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!')
})
tests/example.test.ts
@nuxt/test-utils/playwright的expect和testimport { 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!')
})