Jest中测试Vue动态导入组件的问题排查
问题:Vue动态导入组件在Jest测试中显示
[Function anonymous]导致断言失败 我通过条件动态导入Vue组件并赋值给对象属性,使用Vue的<component :is="">在模板中渲染时功能正常,但在Jest测试用例中无法完成覆盖,控制台显示[Function anonymous]。
函数代码
export default function useCharts() { const {isValid} = storeToRefs(useValidInfo()); const charts = computed(() => [ { id: 'themes', component: isValid.value ? async () => import('./path/component1') : null, grow: '0', title: 'component1', } ]); return { charts } }
测试用例代码
jest.mock('./path/component1', () => 'component1'); describe('useCharts', () => { beforeEach(() => { setActivePinia(createPinia()); }); it('should return charts', () => { const store = useValidInfo(); store.setIsValid(true); const {charts} = useCharts(); expect(charts.value).toEqual([ { id: 'themes', component: component1, // 期望匹配mock组件,但实际得到[Function anonymous] grow: '0', title: 'component1', } ]); }); });
问题原因
代码中将动态导入包装成了匿名异步函数async () => import('./path/component1'),但Jest的mock直接返回字符串'component1',两者类型不匹配;同时每次computed执行都会生成新的匿名函数,直接断言函数引用相等必然失败。
解决方案
方案一:验证函数类型与执行结果(推荐)
修改mock结构匹配Vue动态导入的返回格式,同时分别验证函数存在性与组件内容:
// 修改mock,对应动态导入返回的模块结构(包含default属性) jest.mock('./path/component1', () => ({ default: 'component1' })); describe('useCharts', () => { beforeEach(() => { setActivePinia(createPinia()); }); it('isValid为true时返回包含组件函数的charts', async () => { const store = useValidInfo(); store.setIsValid(true); const { charts } = useCharts(); // 验证component是异步函数 expect(typeof charts.value[0].component).toBe('function'); // 执行函数并解析Promise,验证组件内容 const componentModule = await charts.value[0].component(); expect(componentModule.default).toBe('component1'); }); it('isValid为false时返回component为null的charts', () => { const store = useValidInfo(); store.setIsValid(false); const { charts } = useCharts(); expect(charts.value[0].component).toBeNull(); }); });
方案二:断言对象结构并单独验证组件
如果需要断言整个charts对象的结构,可结合类型断言与组件内容验证:
jest.mock('./path/component1', () => ({ default: 'component1' })); describe('useCharts', () => { beforeEach(() => { setActivePinia(createPinia()); }); it('isValid为true时返回正确的charts结构', async () => { const store = useValidInfo(); store.setIsValid(true); const { charts } = useCharts(); // 断言对象结构,component用expect.any(Function)匹配函数类型 expect(charts.value).toEqual([ { id: 'themes', component: expect.any(Function), grow: '0', title: 'component1', } ]); // 单独验证组件内容 const resolvedComponent = await charts.value[0].component(); expect(resolvedComponent.default).toBe('component1'); }); });
内容的提问来源于stack exchange,提问作者Bhanu Prakash War
相关产品推荐
相关产品推荐

