我正在使用jest和react-native测试进行一些测试,问题是TouchableOpacity无法识别并导致错误
Card.test.js
import Card from "../Card"
import React from 'react';
import { TouchableOpacity } from 'react-native-gesture-handler';
const onePost = { title: "random photo", username: "martin", score: "1233", comments: "4322", creationDate: "6 hours ago", url: "https://m.media-amazon.com/images/I/61FlX89mYGL." }
jest.mock('react-native-gesture-handler', () => {
dropGestureHandler: jest.fn()
})
afterEach(() => {
cleanup();
})
test('render title of the post correctly', () => {
const component = render(<Card {...onePost} />);
expect(component.getByText(onePost.title)).not.toBeNull();
});
字符串
Card.js
import React from "react";
import { Text, Image, View, StyleSheet, Linking,Pressable } from "react-native";
import timeDifference from "../lib/timeDifference";
import { Touchable } from 'react-native-web';
import { TouchableOpacity } from 'react-native-gesture-handler';
export default function Card({ title, username, score, comments, creationDate, image, url }) {
//we render the data from props
return (
<TouchableOpacity
onPress={() => { Linking.openURL('https://www.reddit.com' + url) }}
style={styles.card} >
<View style={{ flexDirection: "row" }}>
<View style={styles.cardImage}>
<Image
style={{ flex: 1 }}
source={{ uri: image }}
/>
</View>
<View style={{ flex: 1, marginHorizontal: 12 }}>
<Text style={styles.cardLocation}>{timeDifference(creationDate)} ago</Text>
<Text
style={styles.cardTitle}>{title}</Text>
</View>
</View>
</TouchableOpacity>
);
}
型
当我运行测试时,它说“无法读取属性'TouchableOpacity'的undefined”,当我更改视图的TouchableOpacity时,它运行正常
1条答案
按热度按时间6ioyuze21#
Jest和React Native Testing Library遇到的问题的解决方案在于您导入
TouchableOpacity
的方式。目前,您正在从'react-native-gesture-handler'
导入它,但您应该直接从'react-native'
导入它。在您的
Card.js
中,将TouchableOpacity
的import语句更改为如下所示:之前
字符串
之后
型
这可以确保您使用的是React Native提供的
TouchableOpacity
组件,它更适合用于Jest和React Native测试库的测试。'react-native-gesture-handler'
库通常用于处理更复杂的手势,可能与您的测试环境不兼容。