首页
/ Nuxt 测试指南:用 @nuxt/test-utils 编写 Nuxt 运行时单元测试与端到端测试

Nuxt 测试指南:用 @nuxt/test-utils 编写 Nuxt 运行时单元测试与端到端测试

2026-09-05 15:29:38作者:卓炯娓

本篇基于 Nuxt 官方文档 Testing 整理,并结合同一仓库自身的测试工程实践展开。Nuxt 通过 @nuxt/test-utils 提供对单元测试与端到端测试的一等支持——这套工具目前正是驱动 Nuxt 仓库自身测试(如 test/ 目录下的用例)以及整个模块生态测试的核心库。读完本篇,你将掌握:基于 Vitest 的 Nuxt 运行时单元测试环境搭建、mountSuspended / mockNuxtImport 等运行时辅助 API 的用法,以及支持 Vitest、Jest、Cucumber、Playwright 多种运行器的端到端测试方案。

安装

@nuxt/test-utils 通过可选的 peer dependencies 让你自行管理其他测试依赖,你可以按项目需要自由选择:

  • DOM 运行时环境:happy-domjsdom 二选一;
  • 测试运行器:vitestcucumberjestplaywright 可任选;
  • playwright-core 仅在使用内置浏览器测试工具(且未使用 @playwright/test 作为运行器)时才需要。
# npm
npm i --save-dev @nuxt/test-utils vitest @vue/test-utils happy-dom playwright-core
# pnpm
pnpm add -D @nuxt/test-utils vitest @vue/test-utils happy-dom playwright-core
# yarn
yarn add --dev @nuxt/test-utils vitest @vue/test-utils happy-dom playwright-core
# bun
bun add --dev @nuxt/test-utils vitest @vue/test-utils happy-dom playwright-core

Nuxt 仓库根目录的 package.json 中即以 catalog:dev 方式声明了 @nuxt/test-utils@vue/test-utils 作为开发依赖,印证了这一组合的实际使用方式。

单元测试

当前 Nuxt 提供的是针对「需要 Nuxt 运行时环境」的代码的单元测试环境,目前仅支持 vitest 作为运行器。

配置步骤

  1. nuxt.config 中加入 @nuxt/test-utils/module(可选)。它会给 Nuxt DevTools 增加 Vitest 集成,支持在开发时直接运行单元测试:

    export default defineNuxtConfig({
      modules: [
        '@nuxt/test-utils/module',
      ],
    })
    
  2. 创建 vitest.config.ts。推荐利用 Vitest projects 精细控制哪类测试运行在哪种环境:

    import { 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',
            },
          }),
        ],
      },
    })
    

    注意:defineVitestProject 只用于 Nuxt 环境测试;端到端测试应配置为普通的 test.environment: 'node' 项目。

  3. 如果你的 Nuxt 环境测试位于 test/nuxt/ 之外,参见后文「测试中的 TypeScript 支持」将其纳入 TypeScript 上下文。

两个实践提示:

  • 在 vitest 配置中导入 @nuxt/test-utils 时,package.json 中需要 "type": "module",或者把配置文件重命名为 vitest.config.mts / vitest.config.mjs
  • 可以通过 .env.test 文件为测试设置环境变量。

Nuxt 仓库自身的 vitest.config.ts 就是一个大规模的多项目示例:其中同时定义了 unitbenchmark、多组 fixture 矩阵项目以及多个 await defineVitestProject(...) 创建的 nuxt / nuxt-universal / nuxt-dev 等项目,并且每个 Nuxt 项目都通过 environmentOptions.nuxt.overrides 注入不同的 Nuxt 配置(如 future.compatibilityVersion: 5),展示了同一套机制如何支撑大规模回归测试。

使用 Nuxt 运行时环境

基于 Vitest projects,你可以精细控制测试运行环境:

  • 单元测试:放在 test/unit/,运行在 Node 环境中,追求速度;
  • Nuxt 测试:放在 test/nuxt/,运行在真实的 Nuxt 运行时环境中。

替代方案:简单配置

如果希望所有测试都运行在 Nuxt 环境中,可以用更基础的配置:

import { defineVitestConfig } from '@nuxt/test-utils/config'
import { fileURLToPath } from 'node:url'

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',也可以按文件选择退出 Nuxt 环境:

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

test('my test', () => {
  // ... 不依赖 Nuxt 环境的测试
})

警告:这种混合方式不被推荐——它会产生一种「Nuxt Vite 插件在运行,但 Nuxt 入口和 nuxtApp 尚未初始化」的中间态环境,容易引发难以调试的错误。

组织你的测试

基于项目制配置,一个典型的目录结构如下:

test/
├── e2e/
│   └── ssr.test.ts
├── nuxt/
│   ├── components.test.ts
│   └── composables.test.ts
└── unit/
    └── utils.test.ts

具体结构可以自由决定,但把 Nuxt 运行时环境测试与 Nuxt 端到端测试隔离开,对测试稳定性很重要。Nuxt 仓库自身的布局(test/nuxt/test/e2e/test/fixtures/)正是遵循这一思路。

测试中的 TypeScript 支持

默认情况下,test/nuxt/tests/nuxt/ 目录中的测试文件会被包含在 Nuxt 应用的 TypeScript 上下文中(即生成 .nuxt/tsconfig.json 的 project references 体系,可参见 TypeScript 概念文档),因此它们能识别 Nuxt 别名(~/@/#imports)并感知 Nuxt 应用中的自动导入。

如果你的 Nuxt 环境测试放在其他目录,可以把它们手动加入 Nuxt 的 TypeScript 上下文:

// nuxt.config.ts
export default defineNuxtConfig({
  typescript: {
    tsConfig: {
      include: [
        // 该路径相对于生成的 .nuxt/tsconfig.json
        '../test/other-nuxt-context/**/*',
      ],
    },
  },
})

重要原则:单元测试不应依赖 Nuxt 运行时特性(如自动导入、composables)。只有当测试确实从源码文件导入内容(如 ~/utils/helpers)时,才为它添加 TypeScript 路径别名支持,而不是为 Nuxt 专属特性添加。

运行测试

# 运行全部测试
npx vitest
# 只运行单元测试
npx vitest --project unit
# 只运行 Nuxt 测试
npx vitest --project nuxt
# watch 模式
npx vitest --watch

警告:在 Nuxt 环境中运行时,测试会跑在 happy-domjsdom 环境里,且测试执行前会先初始化一个全局 Nuxt 应用(包括运行你定义的所有插件、app.vue 中的代码)。因此要格外小心不要在测试中修改全局状态——如果必须修改,测后记得复位。

内置 Mock

@nuxt/test-utils 为 DOM 环境提供了内置 mock,可在 vitest.config.tsenvironmentOptions 中配置:

  • intersectionObserver:默认 true,为 IntersectionObserver API 创建一个无实际功能的哑类;
  • indexedDB:默认 false,开启后使用 fake-indexeddb 创建一个功能完整的 IndexedDB API mock。
import { defineVitestConfig } from '@nuxt/test-utils/config'

export default defineVitestConfig({
  test: {
    environmentOptions: {
      nuxt: {
        mock: {
          intersectionObserver: true,
          indexedDb: true,
        },
      },
    },
  },
})

运行时辅助 API

@nuxt/test-utils/runtime 提供一系列辅助函数,从 Nuxt 仓库的 test/nuxt/ 目录可以看到这些 API 的真实用法。

mountSuspended

mountSuspended 允许在 Nuxt 环境中挂载任意 Vue 组件,支持异步 setup 并可访问 Nuxt 插件提供的注入。底层它包装了 @vue/test-utilsmount,因此 @vue/test-utils 的文档中所有 mount 选项与用法都适用。

// tests/components/SomeComponents.nuxt.spec.ts
import { mountSuspended } from '@nuxt/test-utils/runtime'
import { SomeComponent } from '#components'
import { expect, it } from 'vitest'
import type { Component } from 'vue'

declare module '#components' {
  export const SomeComponent: Component
}

it('can mount some component', async () => {
  const component = await mountSuspended(SomeComponent)
  expect(component.text()).toMatchInlineSnapshot(
    '"This is an auto-imported component"',
  )
})

也可以挂载整个应用:

// tests/App.nuxt.spec.ts
import { renderSuspended } from '@nuxt/test-utils/runtime'
import App from '~/app.vue'

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 的 mount 选项,另加一个 route 属性:初始路由,传 false 可跳过初始路由跳转(默认 /)。

Nuxt 仓库中 test/nuxt/nuxt-time.test.ts 展示了典型用法:通过 mountSuspended 包装一个渲染 NuxtTime 的临时组件,再用 toMatchInlineSnapshot 断言生成的 <time> HTML,从而验证日期本地化与相对时间格式。

renderSuspended

renderSuspended 使用 @testing-library/vue 在 Nuxt 环境中渲染组件,同样支持异步 setup 与插件注入,需要配合 Testing Library 的 screenfireEvent 等工具使用(需自行安装 @testing-library/vue,并在 Vitest 配置 中开启 testing globals 以便自动清理)。传入的组件会被渲染到 <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>"
  `)
})

选项对象接受 @testing-library/vue 的 render 选项,以及 route 属性(初始路由,false 表示跳过初始路由跳转,默认 /)。

mockNuxtImport

mockNuxtImport 用于 mock Nuxt 的自动导入功能,例如 mock useState

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

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

// 你的测试

可以为 mock 显式标注类型以获得类型安全,并借助传给工厂函数的原始实现来 mock 复杂逻辑:

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

mockNuxtImport<typeof useState>('useState', (original) => {
  return (...args) => {
    return { ...original('some-key'), value: 'mocked state' }
  }
})

// 也可以直接传入目标函数
mockNuxtImport(useState, (original) => {
  return (...args) => {
    return { ...original('some-key'), value: 'mocked state' }
  }
})

注意:mockNuxtImport 对同一被 mock 的导入在每个测试文件中只能使用一次——它实际上是一个被转换成 vi.mock 的宏,而 vi.mock 会被提升执行。

如果需要在不同测试之间切换 mock 实现,可以用 vi.hoisted 创建并暴露 mock,再在 mockNuxtImport 中引用,注意在测试前后 restore

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

// 在某个测试内部
useStateMock.mockImplementation(() => {
  return { value: 'something else' }
})

如果只想在单个测试内部 mock 行为,也可以这样做:

import { beforeEach, vi } from 'vitest'
import { mockNuxtImport } from '@nuxt/test-utils/runtime'

mockNuxtImport(useRoute, original => vi.fn(original))

beforeEach(() => {
  vi.resetAllMocks()
})

// 在测试内部
const useRouteOriginal = vi.mocked(useRoute).getMockImplementation()!
vi.mocked(useRoute).mockImplementation(
  (...args) => ({ ...useRouteOriginal(...args), path: '/mocked' }),
)

mockComponent

mockComponent 用于 mock Nuxt 组件:第一个参数是 PascalCase 组件名或组件相对路径,第二个参数是返回 mock 组件的工厂函数。

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

mockComponent('MyComponent', {
  props: {
    value: String,
  },
  setup (props) {
    // ...
  },
})

// 相对路径或别名也可以
mockComponent('~/components/my-component.vue', () => {
  // 或工厂函数
  return defineComponent({
    setup (props) {
      // ...
    },
  })
})

// 也可以用 SFC 重定向到 mock 组件
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 用于创建一个返回 mock 数据的 Nitro 端点,特别适合测试会请求 API 来展示数据的组件。第一个参数是端点路径,第二个参数是返回 mock 数据的工厂函数:

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

registerEndpoint('/test/', () => ({
  test: 'test-field',
}))

默认使用 GET 方法;若需要匹配其他方法,传入对象而非函数:

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 必须在不同的测试环境中运行,因此不能在同一个文件中使用。如果两者都要用,请将测试拆分为不同文件,并二选一地指定环境:用 // @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

如果你更倾向于直接用 @vue/test-utils 做纯 Vue 组件测试(且被测组件不依赖 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. 创建示例组件 app/components/HelloWorld.vue

    <template>
      <p>Hello world</p>
    </template>
    
  5. 编写单元测试 ~/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')
      })
    })
    
  6. 运行测试:npm run test / yarn test / pnpm run test / bun run test

端到端测试

端到端测试支持 Vitest、Jest、Cucumber 和 Playwright 四种运行器。

配置

在每个使用 @nuxt/test-utils/e2e 辅助方法的 describe 块开始之前,需要先调用 setup 建立测试上下文:

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

describe('My test', async () => {
  await setup({
    // 测试上下文选项
  })

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

底层 setup 会在 beforeAllbeforeEachafterEachafterAll 中完成 Nuxt 测试环境的搭建与拆除。

Nuxt 配置项

  • rootDir:被测 Nuxt 应用所在目录。类型 string,默认 '.'
  • configFile:配置文件名。类型 string,默认 'nuxt.config'

超时项

  • setupTimeoutsetupTest 完成工作的允许时长(毫秒),可能包含构建或生成 Nuxt 应用文件。类型 number,默认 120000(Windows 上为 240000);
  • teardownTimeout:拆除测试环境(如关闭浏览器)的允许时长(毫秒)。类型 number,默认 30000

功能项

  • build:是否运行独立的构建步骤。默认 true(禁用 browserserver、或提供 host 时为 false);
  • server:是否启动一个服务器来响应测试请求。默认 true(提供 host 时为 false);
  • port:指定时,将启动的测试服务器端口设为该值。默认 undefined
  • host:指定后直接以该 URL 作为测试目标,不再构建并启动新服务器。适合对已部署环境或已在本地运行的服务器做「真实」端到端测试(可显著缩短测试执行时间),见下方示例。默认 undefined
  • browser:设为真值时,setup 会通过 Playwright 启动一个可被测试套件控制的浏览器。默认 false
  • browserOptions:对象,包含:
    • type:浏览器类型,chromium / firefox / webkit
    • launch:传给 Playwright 启动浏览器的选项对象;
  • runner:测试套件运行器,取值 'vitest' | 'jest' | 'cucumber',默认 'vitest'(官方推荐 Vitest);
  • logLevel:覆盖服务器子进程的 consola 日志级别(可用环境变量 NUXT_TEST_LOG_LEVEL 覆盖)。默认 1
  • captureServerLogs:是否捕获服务器子进程输出而不继承 stdio。为 true(默认)时服务器 stdout/stderr 不会打印到控制台,可通过 getServerLogs() 访问;设为 false 可恢复旧的继承 stdio 行为(本地调试时很有用)。
针对目标 host 的端到端示例

一个常见场景是把测试跑在与生产环境一致的已部署应用上;对本地开发或部署流水线而言,针对一个独立本地服务器测试往往比让测试框架在测试之间重复构建更快。只需给 setup 传入 host 属性:

import { createPage, setup } from '@nuxt/test-utils/e2e'
import { describe, expect, it } 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)
  })
})

辅助 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'

getServerLogs()

返回自上次 startServer() 调用(或 clearServerLogs())以来从服务器子进程 stdout/stderr 捕获的行,仅在 captureServerLogstrue(默认)时可用:

import { expect, it, vi } from 'vitest'
import { $fetch, clearServerLogs, getServerLogs } from '@nuxt/test-utils/e2e'

it('captures console.log output from a server route', async () => {
  clearServerLogs()
  await $fetch('/api/log-test')
  await vi.waitFor(() => {
    expect(getServerLogs().some(line => line.includes('[test] server-log-marker'))).toBe(true)
  })
})

clearServerLogs()

清空已捕获的服务器日志行,适合在多个请求之间使用,以便只针对某次特定操作产生的日志做断言。

浏览器测试

@nuxt/test-utils 内置基于 Playwright 的浏览器测试支持,既可以在测试中编程式调用,也可以直接接入 Playwright 测试运行器。

createPage(url)

vitestjestcucumber 中,可以用 createPage 创建一个配置好的 Playwright 浏览器实例,并(可选地)导航到运行中服务器的某个路径,后续所有 Playwright Page API 都可用:

import { createPage } from '@nuxt/test-utils/e2e'

const page = await createPage('/page')
// 从 `page` 变量可访问全部 Playwright API

使用 Playwright 测试运行器

@nuxt/test-utils/playwright 对 Playwright 测试运行器提供一等支持。先安装依赖:

# npm
npm i --save-dev @playwright/test @nuxt/test-utils
# pnpm
pnpm add -D @playwright/test @nuxt/test-utils
# deno
deno add --dev npm:@playwright/test npm:@nuxt/test-utils

playwright.config.ts 中提供全局 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)),
    },
  },
  // ...
})

测试文件则直接从 @nuxt/test-utils/playwright 导入 expecttest,并可使用注入的 pagegoto fixtures:

// 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!')
})

Nuxt 仓库自身的 playwright.config.ts 展示了更复杂的实际形态:它定义了 webpack / rspack / vite(含 nitroViteEnvironment)× dev / built 的端到端矩阵,为每个项目设置 nuxt.setupTimeoutserverStartTimeout 和注入的 nuxtConfig(如 builderexperimental.appManifest),并通过 testIgnore 区分仅 dev 运行(如 hmr.test.ts)或仅 built 运行(如 spa-preloader-*.test.tschunk-error.test.ts)的用例。而 test/e2e/preview.test.ts 则展示了 test.use({ nuxt: { rootDir, setupTimeout } }) 指向特定 fixture(../fixtures/preview)的写法,配合 goto 验证预览模式的 token 行为。

小结

@nuxt/test-utils 把 Nuxt 应用的测试分为三层清晰的能力:

  1. 纯 Node 单元测试test/unit/):不依赖 Nuxt 运行时,速度最快;
  2. Nuxt 运行时测试test/nuxt/environment: 'nuxt'):全局 Nuxt 应用在测试前完成初始化,配合 mountSuspended / renderSuspended / mockNuxtImport / mockComponent / registerEndpoint 覆盖组件、自动导入与 API 请求场景;
  3. 端到端测试test/e2e/@nuxt/test-utils/e2e 或 Playwright 运行器):通过 setuprootDir / host / browser 等选项构建真实服务器与浏览器环境,用 $fetchcreatePage 等 API 验证服务端渲染与客户端交互。

如果你是模块作者,可进一步参阅 模块作者测试指南;关于测试环境中的 TypeScript 上下文机制,可参考 TypeScript 概念章节

登录后查看全文
热门项目推荐
相关项目推荐

项目优选

收起
kernelkernel
deepin linux kernel
C
33
18
ops-transformerops-transformer
本项目是CANN提供的transformer类大模型算子库,实现网络在NPU上加速计算。
C++
1.12 K
2.72 K
kernelkernel
openEuler内核是openEuler操作系统的核心,既是系统性能与稳定性的基石,也是连接处理器、设备与服务的桥梁。
C
528
588
ops-nnops-nn
本项目是CANN提供的神经网络类计算算子库,实现网络在NPU上加速计算。
C++
906
1.83 K
pytorchpytorch
作为 Ascend for PyTorch 社区的核心组件,TorchNPU 是昇腾专为 PyTorch 打造的深度学习适配插件,使 PyTorch 框架能够直接调用昇腾 NPU,为开发者提供昇腾 AI 处理器的超强算力。
Python
854
1.34 K
docsdocs
暂无描述
Markdown
891
5.78 K
jiuwenswarmjiuwenswarm
JiuwenSwarm 是一款基于openJiuwen开发的智能AI Agent,它能够将大语言模型的强大能力,通过你日常使用的各类通讯应用,直接延伸至你的指尖。
Python
3.53 K
1.01 K
ops-mathops-math
本项目是CANN提供的数学类基础计算算子库,实现网络在NPU上加速计算。
C++
1.34 K
1.45 K
cann-learning-hubcann-learning-hub
CANN 学习中心仓,支持在线互动运行、边学边练,提供教程、示例与优化方案,一站式助力昇腾开发者快速上手。
Jupyter Notebook
987
506
AscendNPU-IRAscendNPU-IR
AscendNPU-IR是基于MLIR(Multi-Level Intermediate Representation)构建的,面向昇腾亲和算子编译时使用的中间表示,提供昇腾完备表达能力,通过编译优化提升昇腾AI处理器计算效率,支持通过生态框架使能昇腾AI处理器与深度调优
C++
540
384