在Vue单元测试中如何等待onMounted生命周期钩子执行完成
问题修复方案
根因分析
你遇到的问题本质是测试代码的执行时序错位:
shallowMount挂载逻辑直接写在describe块的顶层,测试框架运行时会先同步执行所有describe下的顶层代码,之后才会逐个执行it块内的断言逻辑,这就导致你执行断言时,组件的onMounted钩子还未被调度执行。- 即便调用
nextTick、flushPromises,只要挂载操作不在测试用例的执行上下文内,等待逻辑也无法生效。
修复代码
你提供的基础场景不需要额外的异步等待,只需要把挂载逻辑移到测试用例内部即可:
describe('TestComponent', () => { it('expects mounted to be true after mount', () => { const wrapper = shallowMount(TestComponent) expect(wrapper.vm.mounted).toBe(true) }) })
如果实际业务场景中onMounted内存在异步逻辑(接口请求、定时器回调等),可以配合async/await + flushPromises处理:
describe('TestComponent', () => { it('expects mounted related logic finished after mount', async () => { const wrapper = shallowMount(TestComponent) // 等待所有未完成的Promise执行结束 await flushPromises() expect(wrapper.vm.mounted).toBe(true) }) })
如果需要复用组件实例,也可以把挂载逻辑放到beforeEach钩子中:
describe('TestComponent', () => { let wrapper beforeEach(() => { wrapper = shallowMount(TestComponent) }) it('expects mounted to be true after mount', () => { expect(wrapper.vm.mounted).toBe(true) }) })
内容的提问来源于stack exchange,提问作者Inbar Azulay
相关产品推荐
相关产品推荐

