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

如何测试mounted阶段发起API调用的Vue组件?Jest检测不到元素怎么办

问题原因
  • 仅调用jest.mock('axios')只会生成空mock函数,没有为axios.get指定模拟返回值,因此代码中axios.get调用后不会触发then回调,jsonData始终保持初始的空对象,无法拿到预期值。
  • 调用await Vue.$nextTick()的时机不对,且如果没有引入Vue实例会直接报错。你在调用nextTick时,axios的异步回调还未执行,自然拿不到更新后的数据。
  • 初始定义jsonData: {}为对象类型,后续赋值为数组,类型不统一,建议修正初始值避免潜在问题。
修正代码

Welcome.vue 调整

<template>
    <div>
      <h1> {{ title }} </h1>
      <button v-for="button in buttons" :key="button"> {{ button }} </button>
      <br>
      <button v-for="jsons in jsonData" :key="jsons"> {{ jsons }} </button>
    </div>
</template>

<script>
import axios from 'axios'

export default {
  data () {
    return {
      title: 'Welcome page title',
      buttons: ['b1'],
      // 初始值改为和后续赋值一致的数组类型
      jsonData: []
    }
  },
  mounted () {
    this.title = 'new title'
    this.buttons = ['b1', 'b2', 'b3']

    axios.get('https://mocki.io/v1/cda5c244-485e-4f61-8035-ee7d8b8303bc')
      .then(response => (this.jsonData = [response.data[0].value, response.data[1].value, response.data[2].value]))
      .catch(error => console.log(error))
  }
}
</script>

welcome.spec.js 调整

import { shallowMount } from '@vue/test-utils'
import Welcome from '@/components/Welcome.vue'
import axios from 'axios'

jest.mock('axios');

describe("lifecycle methods", () => {
  let wrapper = null
  it("checks that the wrapper is updated",  async () => {
    // 先给axios.get设置模拟返回值,结构和真实接口返回一致
    axios.get.mockResolvedValue({
      data: [
        {value: '1'},
        {value: '2'},
        {value: '3'}
      ]
    })
    wrapper = shallowMount(Welcome);

    expect(wrapper.vm.title).toBe('new title');
    
    expect(wrapper.vm.buttons).toContain('b3');

    expect(axios.get).toHaveBeenCalledWith("https://mocki.io/v1/cda5c244-485e-4f61-8035-ee7d8b8303bc");

    // 等待所有微任务执行完成,确保axios的then回调已经执行
    await Promise.resolve()
    // 再等待dom更新完成
    await wrapper.vm.$nextTick()

    // 验证数据
    expect(wrapper.vm.jsonData).toContain('1')
    // 如果要验证按钮渲染,可以加下面的断言
    const buttons = wrapper.findAll('button')
    // 静态按钮3个 + 接口返回渲染的3个,总共6个
    expect(buttons.length).toBe(6)
    expect(buttons.at(3).text()).toBe('1')
  });
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 04:42:02