Vue3+Quasar v2 Jest单测中globalProperties为undefined如何解决
问题原因
生产环境下你在项目入口(通常是main.js)已经通过app.config.globalProperties挂载了$securityUtils、$axios、$enums等自定义全局属性,也注册了Vuex/Pinia状态管理实例。但Jest运行单元测试时会创建独立的Vue实例,不会自动继承项目里的全局配置,所以组件里通过getCurrentInstance获取的全局属性会是undefined。
解决步骤
你需要在调用shallowMount/mount渲染组件时,手动传入全局配置,注入你用到的所有依赖:
- 模拟自定义全局属性的返回值,可根据测试场景灵活调整返回结果
- 模拟你用到的状态管理库(Vuex/Pinia)的返回数据
- 将所有模拟的依赖传入组件渲染配置的
global字段下
global.mocks是Vue Test Utils v2(对应Vue3)专门用来注入全局属性的配置项,你在这里定义的属性会自动同步到Vue实例的appContext.config.globalProperties下,组件里通过getCurrentInstance也可以正常读取
修改后的测试代码参考:
import { describe, expect, it, jest } from "@jest/globals"; import { installQuasarPlugin } from "@quasar/quasar-app-extension-testing-unit-jest"; import { shallowMount } from "@vue/test-utils"; import App from "../../../src/App.vue"; installQuasarPlugin(); // 模拟自定义全局属性 const mockSecurityUtils = { isAuthenticated: jest.fn().mockReturnValue(true), getTipoToken: jest.fn().mockReturnValue('Bearer'), getToken: jest.fn().mockReturnValue('test-token-123') } const mockEnums = { theme: { DARK: 'dark' } } const mockAxios = { defaults: { headers: { common: {} } } } // 模拟Vuex store const mockStore = { getters: { "auth/configuracoes": JSON.stringify({ TEMA: 'dark' }) } } describe("App", () => { it("sets the correct default data", () => { const wrapper = shallowMount(App, { global: { // 挂载全局属性 mocks: { $securityUtils: mockSecurityUtils, $axios: mockAxios, $enums: mockEnums }, // 注册mock的store plugins: [ { install: (app) => app.config.globalProperties.$store = mockStore } ] } }); const { vm } = wrapper; expect(typeof vm.$q).toBe("object"); expect(typeof vm.$securityUtils).toBe("object"); // 可按需添加断言验证业务逻辑 expect(mockSecurityUtils.isAuthenticated).toHaveBeenCalled() }); });
额外说明
如果多个测试文件都用到相同的全局属性,可以把通用mock配置抽成单独的公共文件,直接导入复用即可,无需每个测试文件重复编写。如果使用Pinia作为状态管理,按照Pinia官方单元测试规范模拟对应store即可。
内容的提问来源于stack exchange,提问作者Gustavo Akira
相关产品推荐
相关产品推荐

