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

Vue Test Utils列表渲染测试:无法遍历元素的问题

Vue组件测试:验证数组Props渲染的列表内容

我在Vue组件测试中需要验证从数组props渲染的列表是否正确,得遍历生成的列表项检查内部数据,但没法用querySelectorAll;而且wrapper.findAll或wrapper.findAllComponents返回的不是能直接用forEach遍历的普通数组。相关组件模板和测试代码如下:

组件模板

<li
  v-for="({ duration, name, description }, index) in works"
  :key="index"
  class="works__item"
>
  <span class="works__duration">{{ duration }}</span>
  <div class="works__infos">
    <strong class="works__name">{{ name }}</strong>
    <span class="works__description">{{ description }}</span>
  </div>
</li>

测试代码

import { mount, config } from "@vue/test-utils";

/**
 * Main component
 */
import Works from '../Works.vue';


config.mocks.$t = key => key

describe('Works', () => {
  it('renders correctly with props', () => {

    /**
     * Defining mock data.
     * -----------------------------------
     */
    const mockData = [
      {
        duration: '2:00',
        name: 'Work 1',
        description: 'Description of work 1'
      },
      {
        duration: '3:30',
        name: 'Work 2',
        description: 'Description of work 2'
      }
    ];

    /**
     * set mock data to the only prop
     * that this component has: work.
     * -----------------------------------
     */
    const wrapper = mount(Works,
      { propsData: { works: mockData },
      attachTo: document.body
    })

    /**
     * Check if the component is rendered.
     * -----------------------------------
     */
    expect(wrapper.exists()).toBe(true)

    /**
     * Check the list
     * -----------------------------------
     */
    const items = wrapper.findAll('.works__item') //findAll返回WrapperArray对象,不是普通数组!
    const items2 = wrapper.querySelectorAll('.works__item')
    console.log({ items });

  })
})

解决方案

wrapper.findAll()返回的是WrapperArray对象,它本身提供了适配的遍历方法,无需强行转成普通数组:

1. 直接使用WrapperArray自带的forEach方法

WrapperArray内置了forEach,可以直接调用遍历每个列表项的Wrapper:

const items = wrapper.findAll('.works__item')
items.forEach((itemWrapper, index) => {
  const mockItem = mockData[index]
  // 验证时长文本
  expect(itemWrapper.find('.works__duration').text()).toBe(mockItem.duration)
  // 验证名称文本
  expect(itemWrapper.find('.works__name').text()).toBe(mockItem.name)
  // 验证描述文本
  expect(itemWrapper.find('.works__description').text()).toBe(mockItem.description)
})

2. 转成普通数组(可选)

如果习惯用数组原生方法,也可以通过Array.from()或扩展运算符把WrapperArray转成普通数组:

const itemsArray = Array.from(wrapper.findAll('.works__item'))
// 或者用扩展运算符
const itemsArray = [...wrapper.findAll('.works__item')]

itemsArray.forEach((itemWrapper, index) => {
  // 同上验证逻辑
})

关于querySelectorAll无法使用的问题

Vue Test Utils的wrapper对象本身没有querySelectorAll方法,若要操作原生DOM元素,可通过wrapper.element获取组件根元素后调用原生方法:

const domItems = wrapper.element.querySelectorAll('.works__item')
domItems.forEach((domItem, index) => {
  const mockItem = mockData[index]
  expect(domItem.querySelector('.works__duration').textContent).toBe(mockItem.duration)
})

但更推荐用WrapperArray的方式,因为能直接使用Vue Test Utils的断言方法,更贴合组件测试场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 01:42:18