类型错误:无法读取未定义的属性“地图”?玩笑/反应本机

问题描述

我有一个图像滑块组件来显示来自我的 Firebase 数据库的图像,如下所示,

import React from 'react';
import Swiper from 'react-native-swiper';
import { View,StyleSheet,Image } from 'react-native'


const ImageSlider = ({images}) => {
    return (
        <Swiper autoplayTimeout={5}
            style={styles.wrapper}
            showsButtons={false}
            loadMinimal={true}
            showsPagination={true}
            paginationStyle={styles.paginationStyle}
            activeDotStyle={styles.activeDotStyle}
            dotStyle={styles.dotStyle}
            loop={true} autoplay={true}
        >
            {images.map((data,index) => {
                return (
                    <View key={index} style={styles.slider}>
                        <Image style={styles.itemImage} source={{ uri: data }} />
                    </View>
                )
            })}
        </Swiper>
    )
}

对于上述组件的测试,我使用了以下测试文件

import React from 'react';
import renderer from 'react-test-renderer';
import ImageSlider from '../../../src/components/imageSlider/ImageSlider';


test('renders correctly',() => {
  const tree = renderer.create(<ImageSlider />).toJSON();
  expect(tree).toMatchSnapshot();
});

当我运行 npm test 命令时出现以下错误

TypeError: Cannot read property 'map' of undefined

谁能帮我解决这个问题,谢谢

解决方法

在您的测试中,您正在创建一个没有任何参数的 ImageSlider

<ImageSlider />

ImageSlider 中,您尝试映射属性 images

images.map( //etc

因为您没有传入 images 参数/属性,所以当您尝试映射它时 images 是未定义的。要解决此问题,请在您的测试中传入 images 的值:

<ImageSlider images={YOUR_TEST_IMAGES_DATA}/>

另一种选择是重新设计 ImageSlider,使其在 images 未定义时正常失败。但是,那么做测试就没有多大意义了(除非测试是为了看看如果没有传入参数会发生什么)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...