![](/img/trans.png)
[英]Not Able to Interact with Button or Text Input on React Native App
[英]React Native Unit Test not able to interact with component
我試圖弄清楚如何設置用戶與反應原生組件的交互,但似乎沒有任何效果。 這是代碼:
data-testid="press"
標簽和包含 function pressActions
的 Pressable 標簽。
在模擬器中測試它時,這部分全部工作。
當我點擊這個組件時,pressActions 確實會運行,所以這個問題與測試有關。
import React, { useState } from 'react'; import { StyleSheet, Pressable, View } from 'react-native'; . . . return ( <Pressable onPress={pressActions}> <View data-testid="press" style={[{...styles.container, marginTop: index === 0? 0: 8 }, getBorderStyle(isForMultipleSelection)]}> <View style={styles.left}> <View> <Text style={styles.leftprice}>{headerText}</Text> </View> <View style={styles.dateContainerStyles}> <Text style={[styles.dateStyles, styles.secondRowCommon]}> {t('dateFormat', { date: startDateDisplay })} </Text> <Text style={{ marginLeft: 5, marginRight: 5 }}> - </Text> <Text style={[styles.dateStyles, styles.secondRowCommon]}>{endDateDisplay}</Text> </View> {override && ( <View style={{ display: 'flex', flexDirection: 'row', alignItems: 'center', paddingTop: 8 }}> <Text style={styles.storeOverrideText}>{t('common:storeOverride')}</Text> </View> )} </View> <View style={styles.right}> <View> <Text style={styles.rightprice}> {isLoyalty && ( <Icon name='loyalty' type='app_icon' color={Colors.primary} style={styles.loyaltyIcon} size={20} tvParallaxProperties={undefined} /> )} {priceText} </Text> </View> <View style={styles.itemQuantityContainer}> <Text style={styles.secondRowCommon}>{quantityText}</Text> </View> </View> </View> </Pressable> ); };
screen.getByTestId('press')
應該定位 testid 字段標記為“press”的元素,即上面的 View 標記
import { fireEvent } from '@testing-library/react-native'; import {render, screen} from '@testing-library/react' import React from 'react'; . . . it('should respond to press', () => { let props: any; props = createTestProps({}); render(<PriceDetails {...props}/>); fireEvent.press(screen.getByTestId('press')); });
我得到的主要錯誤是這個:
TypeError: Cannot read property 'onPress' of undefined fireEvent.press(screen.getByTestId('press')); ^
因此,據我了解,它能夠在調用 getByTestId 時定位組件,但是當在其上使用 fireEvent.press 時,它是未定義的,所以這對我來說真的沒有意義。 提前感謝您的任何建議!
對於將來發現此問題的任何人,我都發現了這個問題。 我試圖使用import {render, screen} from '@testing-library/react'
而我應該將所有內容都保存到@testing-library/react-native'
package,因為那是組件中生成的東西的地方。 讓這兩個包如此相似是愚蠢的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.