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

使用Jest测试含map函数的React组件时出现map未定义报错如何解决

报错原因与修复方案

核心报错原因

你遇到的TypeError: Cannot read property 'map' of undefined错误,本质是组件渲染时productCharacteristics变量为undefined,没有值可以执行map方法。导致这个问题的原因有两个:

  • 测试代码渲染组件时,没有传入组件依赖的productCharacteristics必填属性
  • 组件本身没有做参数为空的防御兼容处理
    另外你给出的组件代码还有一处语法错误:parseIcons函数内直接写了case分支,缺少外层的switch(icon)语句,修复完props问题后还需要补上否则会继续报错。

修复步骤

1. 修改测试代码,传入必填props

你需要先构造测试用的模拟数据,在渲染组件时传入productCharacteristics和page属性:

import React from 'react'
import {screen, render, within} from '@testing-library/react'

import Characteristics from './Characteristics'

// 构造13条测试用模拟数据,匹配你期望的列表长度
const mockCharacteristics = Array.from({length:13}, (_, index) => ({
  id: index,
  icon: ['FaWiFi','FaSwim','FaCoffee','FaUtensils','FaSnowflake','FaSmokingBan','FaCocktail','FaPaw','FaCar','FaConciergeBell','FaDumbbell','FaSpa','FaTv'][index],
  name: `测试服务${index+1}`
}))

// 渲染时传入props
beforeEach(() => render(<Characteristics productCharacteristics={mockCharacteristics} page="home" />));

describe('Test for Characteristics', () => {
    test('Render list of characteristics"', () => {
        const list = screen.getByRole("list", {
            name: "",
        })
        const {getAllByRole} = within(list)
        const items = getAllByRole("listitem")
        expect(items.length).toBe(13)
    });
});

2. 给组件加防御兼容处理

为了避免后续使用时不传参数就崩溃,可以在解构props时给默认值:

// 解构时给空数组作为默认值,保证即使不传props也不会出现undefined
const { productCharacteristics = [], page = "default" } = props;

3. 修复parseIcons函数的语法错误

补上缺失的switch语句:

function parseIcons(icon) {
  switch(icon) { // 补上这行
    case 'FaWiFi':
        return <FaWifi className="service-icon-home" />
    case 'FaSwim':
        return <FaSwimmer className="service-icon-home swimmer-icon" />
    // 剩余case保持不变
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 07:06:03