You need to enable JavaScript to run this app. 如何为Vue2 Composition API中onMounted钩子内的函数编写Jest测试用例
优惠活动
大模型
产品
解决方案
定价
更多

如何为Vue2 Composition API中onMounted钩子内的函数编写Jest测试用例

Vue2 + Composition API 中onMounted调用函数的测试用例编写方案

测试基于@vue/test-utils@1.x(适配Vue2版本) + Jest/Vitest 实现,核心思路是Mock外部依赖避免真实请求,分别验证钩子触发逻辑和函数本身的业务逻辑。

前置配置

测试前需要先Mock外部依赖,避免发起真实GraphQL请求:

  • 对apolloClient.getGraphqlData进行Mock,自定义返回成功/失败结果
  • 如果需要验证getUsers的调用时机,可以用jest.spyOn(或vitest的vi.spyOn)监听函数调用

测试用例1:验证onMounted触发getUsers调用

核心验证组件挂载完成后,getUsers会被执行一次:

import { shallowMount, createLocalVue } from '@vue/test-utils'
import VueCompositionAPI from '@vue/composition-api'
import MyComponent from './MyComponent.vue'
import * as apolloClient from './path/to/apollo-client'

const localVue = createLocalVue()
localVue.use(VueCompositionAPI)

// 监听getGraphqlData调用,也可以直接spyOn组件内的getUsers
jest.spyOn(apolloClient, 'getGraphqlData').mockResolvedValue({
  data: { users: [] }
})

describe('MyComponent', () => {
  it('calls getUsers when component is mounted', () => {
    shallowMount(MyComponent, { localVue })
    expect(apolloClient.getGraphqlData).toHaveBeenCalledTimes(1)
    // 如果能直接访问getUsers,也可以直接断言getUsers被调用
  })
})

测试用例2:验证getUsers请求成功逻辑

验证接口返回正常时,users响应式变量会被正确赋值:

it('fills users array when getUsers query succeeds', async () => {
  const mockUsers = [{ id: 1, username: 'testuser' }]
  jest.spyOn(apolloClient, 'getGraphqlData').mockResolvedValue({
    data: { users: mockUsers }
  })

  const wrapper = shallowMount(MyComponent, { localVue })
  // 等待异步请求执行完成
  await wrapper.vm.$nextTick()

  // 如果users是组件暴露的响应式变量,可以直接断言
  expect(wrapper.vm.users).toEqual(mockUsers)
})

测试用例3:验证getUsers异常处理逻辑

验证接口请求失败时,错误会被正确捕获并打印:

it('logs error when getUsers query fails', async () => {
  const mockError = new Error('Network error')
  jest.spyOn(apolloClient, 'getGraphqlData').mockRejectedValue(mockError)
  // 监听console.log调用
  const consoleSpy = jest.spyOn(console, 'log').mockImplementation()

  const wrapper = shallowMount(MyComponent, { localVue })
  await wrapper.vm.$nextTick()

  expect(consoleSpy).toHaveBeenCalledWith('Error while receiving users', mockError)
  // 恢复console.log的原始实现
  consoleSpy.mockRestore()
})

注意事项

如果组件内的getUsers和users没有对外暴露,可以在组件代码中通过defineExpose(Vue2 Composition API支持该语法)将需要测试的变量/方法暴露出来,方便测试用例访问。

内容的提问来源于stack exchange,提问作者Purni

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.14 17:36:05