1

I'm trying to write test cases in React Native using Jest and Testing Library. I have a .map function where it renders a component with TouchableOpacity.

{data.map((item, index) => (
    <SafeAreaView key={index}>
        <ItemView data={item} index={index} />
        {index >= data.length - 1 ? (
            <View style={{ marginTop: 16 }} />
        ) : (
            <View style={styles.itmSeperator} />
        )}
    </SafeAreaView>
))}

The ItemView looks like

const ItemView = ({ data, index }) => (
    <TouchableOpacity
        testID="TouchablePress"
        onPress={() => onPress(data)}
        style={{
            alignItems: "center",
            paddingVertical: 16,
        }}
    >
        <Text style={styles.text}>{data.name}</Text>
    </TouchableOpacity>
);

For the above if I call fireEvent(getByTestId("TouchablePress"), "press"); in tests file the test is getting file stating found multiple component with same id "TouchablePress".

Any suggestions on how to cover this test without getting failed?

juliomalves
  • 42,130
  • 20
  • 150
  • 146
Sai kiran
  • 237
  • 3
  • 15
  • 2
    You can retrieve them all using `getAllByTestId` then select the first one to actually fire the `press` action on. _OR_ have the `testID`s different for each `ItemView` based off their `index` value, then select the desired one. – juliomalves Jun 20 '21 at 16:27
  • @Saikiran see [React Testing Library: Test if Elements have been mapped/rendered](https://stackoverflow.com/a/68201001/6243352). The touchable opacity isn't critical here, it's using `getAllByTestId` as shown in the link and as Julio describes above. – ggorlen Jun 30 '21 at 20:22

0 Answers0