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

使用Jest测试React组件时JSON数据渲染报错如何解决

错误根因

你的ImageGalleryStatic组件运行依赖必填的product属性,测试代码渲染组件时未传入该属性,导致组件内部解构出的product值为undefined,访问product.images就会抛出Cannot read property 'images' of undefined类型错误。

排查步骤
  • 确认组件props依赖:组件需要接收包含images数组的product属性,数组每个元素需包含url字段
  • 核对测试传参:测试代码中shallow(<ImageGalleryStatic />)未传入任何props,符合错误特征
  • 验证JSON导入有效性:如果已经准备了测试用的JSON产品数据,检查导入语句的路径、文件名拼写是否正确,导入的变量结构是否符合组件要求
解决方法

方式1:导入本地JSON数据传入组件

假设你的测试用产品数据存放在同级目录的testProduct.json中,修改测试文件代码如下:

import React from 'react'
import {render} from '@testing-library/react'
import Enzyme from "enzyme";
import ImageGalleryStatic from './ImageGalleryStatic'
// 替换为你实际的JSON文件路径
import testProduct from './testProduct.json'
import Adapter from "enzyme-adapter-react-16"

const { shallow } = Enzyme;

Enzyme.configure({ adapter: new Adapter() })

// 修正describe的测试对象名称,之前误写为RatingStars
describe('Test for ImageGalleryStatic', () => {
    test("renders correctly", () => {
        // 传入必填的product属性
        shallow(<ImageGalleryStatic product={testProduct} />);
    });
});

方式2:手动构造Mock数据(无需依赖外部JSON)

如果不想引入外部文件,可以直接在测试代码中构造符合结构的模拟数据:

const mockProduct = {
  images: [
    {url: 'test-img-1.jpg'},
    {url: 'test-img-2.jpg'},
    {url: 'test-img-3.jpg'},
    {url: 'test-img-4.jpg'},
    {url: 'test-img-5.jpg'}
  ]
}

// 渲染组件时传入mock数据
shallow(<ImageGalleryStatic product={mockProduct} />);

可选优化:组件兼容空值场景

如果希望组件在未传入product时也不会崩溃,可以在组件内部做兼容处理:

function ImageGalleryStatic(props) {
    // 解构时给默认值
    const { product = {} } = props;
    // 访问属性时使用可选链+默认占位值
    return (
        <>
            <section className="photo-gallery">
                <div className="product-photos">
                    <div className="photos-container">
                        <figure className="photo">
                            <img src={product?.images?.[0]?.url || '默认占位图路径'} alt="imagen del alojamiento" />
                        </figure>
                        {/* 其余image标签同理做可选链处理 */}
                        <Modal product={product} divider=" de "/>
                    </div>
                </div>
            </section>
            <section className="photo-gallery-tablet">
                <ImageGallery productImages={product?.images || []} divider="/" showThumbs={false}/>
            </section>
        </>
    )
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 11:06:03