Vitest测试Nuxt页面时如何Mock definePageMeta解决未定义报错
问题原因
definePageMeta是Nuxt框架专属的编译期宏,不属于Vue原生API,直接在Vitest中挂载组件时,缺少Nuxt的编译转换逻辑,会导致运行时识别不到该API,抛出undefined报错。
解决方案
方案1:使用官方测试工具(推荐)
Nuxt官方提供的@nuxt/test-utils已经内置了所有Nuxt专属宏、自动导入API的mock和编译处理,不需要手动写桩代码,适配性最好。
- 安装依赖
npm i -D @nuxt/test-utils vitest @vue/test-utils happy-dom
- 替换Vitest配置文件(
vitest.config.ts)内容,使用Nuxt导出的配置方法:
import { defineVitestConfig } from '@nuxt/test-utils/config' export default defineVitestConfig({ test: { environment: 'happy-dom', } })
- 修改测试用例,用
mountSuspended替代原mount方法,同时修正原代码里的断言错误(组件实际渲染文本为Hello World,原断言写的是Hello Vitest):
import { describe, expect, it } from 'vitest'; import Index from '../pages/test.vue'; import { mountSuspended } from '@nuxt/test-utils/runtime'; describe('renders the test component', () => { it('renders properly', async () => { const wrapper = await mountSuspended(Index); expect(wrapper.text()).toContain('Hello World'); }); });
方案2:手动全局Mock宏
如果不想引入官方测试工具,可以直接在Vitest运行时全局StubdefinePageMeta解决未定义问题。
- 新建测试setup文件,比如路径为
tests/setup.ts,写入全局mock逻辑:
import { vi } from 'vitest' // 全局桩替换definePageMeta vi.stubGlobal('definePageMeta', vi.fn()) // 如果测试中用到其他Nuxt专属宏(比如useAsyncData、defineNuxtComponent等),也可以在这里统一mock
- 在
vitest.config.ts中引入该setup文件:
import { defineConfig } from 'vitest/config' import vue from '@vitejs/plugin-vue' export default defineConfig({ plugins: [vue()], test: { environment: 'happy-dom', setupFiles: ['./tests/setup.ts'], } })
- 原测试用例不需要修改挂载逻辑,只需要修正断言文本即可运行。如果需要验证页面meta配置是否正确,可以在测试中加mock断言:
import { describe, expect, it } from 'vitest'; import Index from '../pages/test.vue'; import { mount } from '@vue/test-utils'; describe('renders the test component', () => { it('renders properly', () => { const wrapper = mount(Index); expect(wrapper.text()).toContain('Hello World'); // 验证definePageMeta入参符合预期 expect(global.definePageMeta).toHaveBeenCalledWith(expect.objectContaining({ layout: 'xyz', title: 'test component' })) }); });
注意:手动mock方案仅解决API未定义的报错,不会实现Nuxt宏的原生逻辑,如果测试涉及路由、布局、数据请求等Nuxt核心能力,还是优先选择官方测试工具方案。
内容的提问来源于stack exchange,提问作者CandleCoder
相关产品推荐
相关产品推荐

