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

Jest测试Vuetify v-img尺寸时无法获取渲染生成的DOM元素如何解决

问题原因梳理
    1. 测试用了shallowMount:这个API会自动stub所有子组件,v-img作为Vuetify的组件会被替换为空的占位符,不会渲染出内部真实的div结构,自然找不到对应的元素
    1. 组件本身存在语法错误:
    • template根标签是<span class="footerImagesLayout">,结束标签却写了</div>,标签不匹配
    • data函数没有return对象,属性定义无效,还重复声明了两次oma_logo_width,缺少oma_logo_height的定义
    1. Vuex Store配置错误:你把根state直接放到了modules配置项里,导致组件读取$store.state.app的时候拿不到预期数据,组件渲染异常
    1. 选择器匹配逻辑问题:就算v-img正常渲染,生成的div也不一定是.footerImagesLayout的直接子元素,和Vuetify的版本渲染逻辑有关
修复步骤

第一步:修正footer.vue的语法错误

<template>
  <!-- 结束标签对应修改为span -->
  <span class="footerImagesLayout">
    <v-img 
     :height="easg_logo_height"
     :src="$store.state.app.easg_logo.src"
     :width="easg_logo_width"
     contain
     />
    <v-img 
     :height="oma_logo_height"
     :src="$store.state.app.oma_logo.src"
     :width="oma_logo_width"
     contain
     />
  </span>
</template>
<script>
export default {
  data(){
    // 补全return,修正重复定义的问题
    return {
      easg_logo_width: this.$store.state.app.easg_logo.top.width, 
      easg_logo_height: this.$store.state.app.easg_logo.top.height,
      oma_logo_width: this.$store.state.app.oma_logo.top.width,
      oma_logo_height: this.$store.state.app.oma_logo.top.height,
    }
  }
}
</script>

第二步:修正测试代码的配置

核心修改点:

  • 把shallowMount换成mount,让子组件正常渲染
  • 修复Vuex Store的配置,去掉多余的modules嵌套
  • 可以直接获取VImg组件实例验证props,比查DOM更简单高效
import {mount, createLocalVue} from '@vue/test-utils'
import Vuex from 'vuex';
import Footer from '@components/layouts/default/footer'
import Vuetify from 'vuetify';

const vuetify = new Vuetify();
const localVue = createLocalVue();
localVue.use(Vuex);

describe("Footer tests", ()=> {
  let wrapper;
  let store;
  let state;

  beforeEach(() => {
    state= {
      app: {
        easg_logo:{
          src: "~/assets/images/easg.jpg",
          text: "EASG", 
          top:{
            height: 72,
            width: 82
          }
        },
        oma_logo:{
          src: "~/assets/images/oma.jpg",
          text: "OMA", 
          top:{
            height: 72,
            width: 82
          }
        }
      }
    }
    // 修复store配置,根state直接传,不要套modules
    store = new Vuex.Store({
      state
    })
  })

  test('验证v-img尺寸设置正确', ()=> {
    wrapper = mount(Footer, {store, localVue, vuetify})
    // 直接获取VImg组件验证props
    const imgs = wrapper.findAllComponents({name: 'VImg'})
    expect(imgs.at(0).vm.width).toBe(82)
    expect(imgs.at(0).vm.height).toBe(72)
    expect(imgs.at(1).vm.width).toBe(82)
    expect(imgs.at(1).vm.height).toBe(72)

    // 如果一定要验证渲染后的style属性,可以先打印wrapper.html()确认结构后调整选择器
    // console.log(wrapper.find('.footerImagesLayout .v-image').element.style)
  });
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 01:06:08