Lzh on GitHub

测试

了解如何测试您的 Nuxt 应用程序。
如果您是模块作者,您可以在 模块作者指南 中找到更具体的信息。

Nuxt 通过 @nuxt/test-utils 为您的 Nuxt 应用程序提供一流的端到端和单元测试支持。@nuxt/test-utils 是一个测试实用程序和配置库,目前为 我们 在 Nuxt 本身使用的测试 以及整个模块生态系统中的测试提供支持。

安装

为了让您管理其他测试依赖项,@nuxt/test-utils 附带各种可选的对等依赖项。例如:

  • 您可以在 happy-domjsdom 之间选择一个作为运行时 Nuxt 环境
  • 您可以在 vitestcucumberjestplaywright 之间选择一个作为端到端测试运行器
  • 如果您希望使用内置的浏览器测试实用程序(并且没有使用 @playwright/test 作为测试运行器),则只需要 playwright-core
npm i --save-dev @nuxt/test-utils vitest @vue/test-utils happy-dom playwright-core

单元测试

我们目前提供一个用于单元测试需要 Nuxt 运行时环境的代码的环境。它目前 仅支持 vitest (尽管欢迎贡献以添加其他运行时)。

Setup

  1. @nuxt/test-utils/module 添加到您的 nuxt.config 文件中(可选)。它为您的 Nuxt DevTools 添加了 Vitest 集成,该集成支持在开发中运行您的单元测试。
    export default defineNuxtConfig({
      modules: [
        '@nuxt/test-utils/module'
      ]
    })
    
  2. 创建一个包含以下内容的 vitest.config.ts
    import { defineVitestConfig } from '@nuxt/test-utils/config'
    
    export default defineVitestConfig({
      // any custom Vitest config you require
    })
    
在您的 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.tsmy-file.nuxt.spec.ts),或者直接在测试文件中添加 @vitest-environment nuxt 作为注释来选择加入 Nuxt 环境。

// @vitest-environment nuxt
import { test } from 'vitest'

test('my test', () => {
  // ... test with Nuxt environment!
})

或者,您可以在 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',
    // 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',则可以根据需要在每个测试文件中选择 退出 默认环境

// @vitest-environment node
import { test } from 'vitest'

test('my test', () => {
  // ... test without Nuxt environment!
})
当您在 Nuxt 环境中运行测试时,它们将在 happy-domjsdom 环境中运行。在您的测试运行之前,将初始化一个全局 Nuxt 应用程序(包括,例如,运行您在 app.vue 中定义的任何插件或代码)。这意味着您应该特别注意不要在测试中改变全局状态(或者,如果需要,之后将其重置)。

🎭 内置 Mock

@nuxt/test-utils 为 DOM 环境提供了一些内置的 Mock。

intersectionObserver

默认为 true,创建一个没有任何 IntersectionObserver API 功能的虚拟类

indexedDB

默认为 false,使用 fake-indexeddb 创建 IndexedDB API 的功能性 mock

这些可以在您的 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 插件的注入。

在底层,mountSuspended 包装了 @vue/test-utils 中的 mount,因此您可以查看 Vue Test Utils 文档 以了解更多关于您可以传递的选项以及如何使用此实用程序的信息。

例如:

// @noErrors
import { it, expect } 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 { it, expect } 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>"
    `)
})

renderSuspended

renderSuspended 允许您使用 @testing-library/vue 在 Nuxt 环境中渲染任何 Vue 组件,从而允许异步设置和访问来自您的 Nuxt 插件的注入。

这应该与 Testing Library 的实用程序(例如 screenfireEvent)一起使用。在您的项目中安装 @testing-library/vue 以使用这些实用程序。

此外,Testing Library 还依赖于用于清理的测试全局变量。您应该在您的 Vitest 配置 中启用这些全局变量。

传入的组件将在 <div id="test-wrapper"></div> 中渲染。

示例:

// @noErrors
import { it, expect } 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 '@09.testing-library/vue'

it('can render some component', async () => {
  await renderSuspended(SomeComponent)
  expect(screen.getByText('This is an auto-imported component')).toBeDefined()
})
// @noErrors
import { it, expect } 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>"
  `)
})

mockNuxtImport

mockNuxtImport 允许您模拟 Nuxt 的自动导入功能。例如,要模拟 useStorage,您可以这样做:

import { mockNuxtImport } from '@nuxt/test-utils/runtime'

mockNuxtImport('useStorage', () => {
  return () => {
    return { value: 'mocked storage' }
  }
})

// your tests here
每个测试文件中的每个模拟导入只能使用一次 mockNuxtImport。它实际上是一个宏,会被转换为 vi.mock,而 vi.mock 会被提升,如此处所述。

如果您需要模拟 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' }
})

mockComponent

mockComponent 允许您模拟 Nuxt 的组件。 第一个参数可以是帕斯卡命名法的组件名称,也可以是组件的相对路径。 第二个参数是一个工厂函数,该函数返回模拟的组件。

例如,要模拟 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', async () => {
  // 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' })
})

注意: 如果您的组件中的请求发送到外部 API,您可以使用 baseURL,然后使用 Nuxt Environment Override Config ($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 { setup, $fetch } from '@nuxt/test-utils/e2e'

await setup({
  setupTimeout: 10000,
})

// ...

使用 @vue/test-utils

如果您更喜欢单独使用 @vue/test-utils 在 Nuxt 中进行单元测试,并且您只测试不依赖于 Nuxt composables、自动导入或上下文的组件,您可以按照以下步骤进行设置。

  1. 安装所需的依赖项
    npm i --save-dev vitest @vue/test-utils happy-dom @vitejs/plugin-vue
    
  2. 创建一个包含以下内容的 vitest.config.ts
    import { defineConfig } from 'vitest/config'
    import vue from '@vitejs/plugin-vue'
    
    export default defineConfig({
      plugins: [vue()],
      test: {
        environment: 'happy-dom',
      },
    });
    
  3. 在您的 package.json 中为测试添加一个新命令
    "scripts": {
      "build": "nuxt build",
      "dev": "nuxt dev",
      ...
      "test": "vitest"
    },
    
  4. 创建一个简单的 <HelloWorld> 组件 components/HelloWorld.vue,内容如下:
    <template>
      <p>Hello world</p>
    </template>
    
  5. 为这个新创建的组件 ~/components/HelloWorld.spec.ts 创建一个简单的单元测试:
    import { describe, it, expect } 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')
      })
    })
    
  6. 运行 vitest 命令
    npm run test
    

恭喜,您已准备好开始在 Nuxt 中使用 @vue/test-utils 进行单元测试!祝您测试愉快!

端到端测试

对于端到端测试,我们支持 VitestJestCucumberPlaywright 作为测试运行器。

设置

在每个利用 @nuxt/test-utils/e2e 辅助方法的 describe 块中,您需要在开始之前设置测试上下文。

test/my-test.spec.ts
import { describe, test } from 'vitest'
import { setup, $fetch } from '@nuxt/test-utils/e2e'

describe('My test', async () => {
  await setup({
    // test context options
  })

  test('my test', () => {
    // ...
  })
})

在幕后,setupbeforeAllbeforeEachafterEachafterAll 中执行许多任务,以正确设置 Nuxt 测试环境。

请为 setup 方法使用以下选项。

Nuxt 配置

  • rootDir: 要测试的 Nuxt 应用程序目录的路径。
    • Type: string
    • Default: '.'
  • configFile: 配置文件的名称。
    • Type: string
    • Default: 'nuxt.config'

时序

  • setupTimeout: 允许 setupTest 完成其工作的时间量(以毫秒为单位)(这可能包括构建或生成 Nuxt 应用程序的文件,具体取决于传递的选项)。
    • Type: number
    • Default: 60000

功能

  • build: 是否运行单独的构建步骤。
    • 类型: boolean
    • 默认值: true (false if browser or server is disabled, or if a host is provided)
  • server: 是否启动服务器以响应测试套件中的请求。
    • 类型: boolean
    • 默认值: true (false if a host is provided)
  • port: 如果提供,将启动的测试服务器端口设置为该值。
    • 类型: number | undefined
    • 默认值: undefined
  • host: 如果提供,则使用 URL 作为测试目标,而不是构建和运行新服务器。这对于针对已部署的应用程序版本或针对已运行的本地服务器运行“真实”的端到端测试非常有用(这可以显着缩短测试执行时间)。请参见下面的 目标主机端到端示例
    • 类型: string
    • 默认值: undefined
  • browser: 在底层,Nuxt 测试实用程序使用 playwright 执行浏览器测试。如果设置此选项,将启动浏览器,并且可以在后续的测试套件中对其进行控制。
    • 类型: boolean
    • 默认值: false
  • browserOptions
    • 类型: 具有以下属性的 object
      • type: 要启动的浏览器类型 - chromiumfirefoxwebkit 之一
      • launch: 将在启动浏览器时传递给 playwright 的选项 object。请参见 完整的 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('login page', async () => {
  await setup({
    host: 'http://localhost: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)
  })
})

APIs

$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)

vitestjestcucumber 中,您可以使用 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

您可以提供全局 Nuxt 配置,其配置详细信息与本节前面提到的 setup() 函数相同。

playwright.config.ts
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))
    }
  },
  // ...
})
Read more in 查看完整的示例配置.

然后,您的测试文件应直接使用 @nuxt/test-utils/playwright 中的 expecttest

tests/example.test.ts
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 服务器:

tests/example.test.ts
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!')
})