TypeError: Cannot read property 'map' of undefined ? Jest / React Native

784 Views Asked by At

I have an image slider component to display images from my Firebase database as follows ,

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>
    )
}

For test above component I used follwing test file ,

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();
});

When I'm run npm test command and after I got following error

TypeError: Cannot read property 'map' of undefined

Can anyone help me to slove this problem , Thank you

1

There are 1 best solutions below

0
On BEST ANSWER

In your test, you're creating an ImageSlider without any parameters:

<ImageSlider />

In ImageSlider, you try to map the property images:

images.map( //etc

Because you didn't pass in an images parameter/property, images is undefined when you try to map it. To solve, this pass in value for images in your test:

<ImageSlider images={YOUR_TEST_IMAGES_DATA}/>

The other option is to redesign ImageSlider so that it fails gracefully if images is undefined. But, then there wouldn't be much a point in doing the test (unless the test was to see what happens if no parameter is passed in)