React-Native测试库/Jest:无法读取属性“TouchableOpacity”

fivyi3re  于 6个月前  发布在  Jest
关注(0)|答案(1)|浏览(81)

我正在使用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时,它运行正常

6ioyuze2

6ioyuze21#

Jest和React Native Testing Library遇到的问题的解决方案在于您导入TouchableOpacity的方式。目前,您正在从'react-native-gesture-handler'导入它,但您应该直接从'react-native'导入它。
在您的Card.js中,将TouchableOpacity的import语句更改为如下所示:

之前

import { TouchableOpacity } from 'react-native-gesture-handler';

字符串

之后

import { TouchableOpacity } from 'react-native';


这可以确保您使用的是React Native提供的TouchableOpacity组件,它更适合用于Jest和React Native测试库的测试。'react-native-gesture-handler'库通常用于处理更复杂的手势,可能与您的测试环境不兼容。

相关问题