Jest.js 找不到具有testID的元素

s3fp2yjn  于 2023-02-01  发布在  Jest
关注(0)|答案(2)|浏览(257)

我正在构建一个React Native应用。在我的GigsByDay组件中,有一个TouchableOpacity元素,当按下该元素时,会将用户引导到GigDetails屏幕。我正在尝试使用Jest和React Native Testing Library测试此特定功能。
我编写了以下测试,但收到了错误:
找不到testID为的元素:今日演出卡
测试如下:

describe("gigs by week component", () => {
  let navigation;

  beforeEach(() => {
    navigation = { navigate: jest.fn() };
  });

  test("that when gig listing is pressed on it redirects user to Gig Details page", () => {
    render(<GigsByDay navigation={navigation} />);
    const gigCard = screen.getByTestId("gigs-today-card");
    fireEvent.press(gigCard);
    expect(navigation.navigate).toHaveBeenCalledWith("GigDetails");
  });
});

其测试的元素如下所示:

<TouchableOpacity
        testID="gigs-today-card"
        style={styles.gigCard}
        onPress={() =>
          navigation.navigate('GigDetails', {
            venue: item.venue,
            gigName: item.gigName,
            blurb: item.blurb,
            isFree: item.isFree,
            image: item.image,
            genre: item.genre,
            dateAndTime: {...item.dateAndTime},
            tickets: item.tickets,
            id:item.id
          })
        }>
        <View style={styles.gigCard_items}>
          <Image
            style={styles.gigCard_items_img}
            source={require('../assets/Icon_Gold_48x48.png')}
          />
          <View>
            <Text style={styles.gigCard_header}>{item.gigName}</Text>
            <Text style={styles.gigCard_details}>{item.venue}</Text>
          </View>
        </View>
      </TouchableOpacity>

我试过如下修正我的测试,但没有成功:

test("that when gig listing is pressed on it redirects user to Gig Details page", async () => {
    render(<GigsByDay navigation={navigation} />);
    await waitFor(() => {
    expect(screen.getByTestId('gigs-today-card')).toBeTruthy()
})
    const gigCard = screen.getByTestId("gigs-today-card");
    fireEvent.press(gigCard);
    expect(navigation.navigate).toHaveBeenCalledWith("GigDetails");
  });
});

对于如何解决这个问题有什么建议吗?我还尝试将testID分配给TouchableOpacity元素中的视图。
下面是整个GigsByDay组件的上下文:

import { FC } from 'react';
import { FlatList,TouchableOpacity,StyleSheet,View,Image,Text } from 'react-native'
import { listProps } from '../routes/homeStack';
import { GigObject } from '../routes/homeStack';

type ListScreenNavigationProp = listProps['navigation']

interface Props {
  gigsFromSelectedDate: GigObject[],
  navigation: ListScreenNavigationProp
}

const GigsByDay:FC<Props> = ({ gigsFromSelectedDate, navigation }):JSX.Element => (
  <FlatList
    testID='gigs-today'
    data={gigsFromSelectedDate}
    keyExtractor={item => item.id}
    renderItem={({ item }) => (
      <TouchableOpacity
        testID="gigs-today-card"
        style={styles.gigCard}
        onPress={() =>
          navigation.navigate('GigDetails', {
            venue: item.venue,
            gigName: item.gigName,
            blurb: item.blurb,
            isFree: item.isFree,
            image: item.image,
            genre: item.genre,
            dateAndTime: {...item.dateAndTime},
            tickets: item.tickets,
            id:item.id
          })
        }>
        <View style={styles.gigCard_items}>
          <Image
            style={styles.gigCard_items_img}
            source={require('../assets/Icon_Gold_48x48.png')}
          />
          <View>
            <Text style={styles.gigCard_header}>{item.gigName}</Text>
            <Text style={styles.gigCard_details}>{item.venue}</Text>
          </View>
        </View>
      </TouchableOpacity>
    )}
  />
)
5jvtdoz2

5jvtdoz21#

请传递带有一些模拟数组数据的gigsFromSelectedDate prop,以便平面列表根据数组长度呈现其元素。目前,您没有传递它。请检查以下代码。

test('that when gig listing is pressed on it redirects user to Gig Details page', () => {
    const mockData = [{venue: 'some venue', 
                      gigName: 'some gigName, 
                      blurb: 'some blurb',
                      isFree: 'some isFree', 
                      image: 'some image', 
                      genre: 'some genre', 
                      dateAndTime: {}, 
                      tickets: ['some ticket'],
                     id: 'some id'}]
    const screen = render(<GigsByDay navigation={navigation} gigsFromSelectedDate={mockData} />);
    const gigCard = screen.getByTestId('gigs-today-card');
    fireEvent.press(gigCard);
    expect(navigation.navigate).toHaveBeenCalledWith('GigDetails');
  });
vhipe2zx

vhipe2zx2#

您是否安装了以下软件包?请检查您的Package.json
“@测试库/本机jest”:“^5.4.1”
如果没有,请安装它,然后将它导入到您编写测试用例的地方。
导入“@测试库/jest本机/扩展预期”;
如果它已存在于中,请尝试以下jest-native属性。
const gigCard =屏幕.按测试ID查询(“今天的千兆卡”);
const gigCard =屏幕.findByTestId(“今天的千兆位卡”);

相关问题