You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue3项目中如何测试指定函数是否使用async关键字声明

实现方案

核心判断逻辑

所有通过async关键字声明的函数,原生JS即可直接识别,不需要额外依赖:

// 工具函数:判断入参是否为async函数
const isAsyncFunction = (func) => {
  return Object.prototype.toString.call(func) === '[object AsyncFunction]'
}

验证逻辑:

  • 普通函数const updateRoute = () => {}调用工具返回false,断言失败
  • async函数const updateRoute = async () => {}调用工具返回true,断言通过

测试实现示例(Jest + Vue Test Utils)

前置条件

安装基础依赖:

npm install jest @vue/test-utils@next @vue/vue3-jest babel-jest -D

场景1:测试选项式API组件的方法

组件内updateRoute定义在methods中,可直接从挂载后的实例获取:

import { mount } from '@vue/test-utils'
import YourComponent from './YourComponent.vue'

test('updateRoute 是async函数', () => {
  const wrapper = mount(YourComponent)
  // 从实例获取methods里的函数
  const updateRoute = wrapper.vm.updateRoute
  expect(isAsyncFunction(updateRoute)).toBe(true)
})

场景2:测试

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 15:24:03