typescriptreact-nativejestjsbabel-jestreact-test-renderer

TypeError: Cannot read property 'params' of undefined Jest Testing - React Native


I have created a test file to test my following "BiddingScreen",

const BiddingScreen = ({ route, navigation }) => {

const { currentBid } = route.params;


return (
    <SafeAreaView style={styles.main}>
        <Header title="BID Here" navigation={navigation} />
        <View style={styles.container}>
            <Text style={styles.currentBid}>{CurrentBid}$</Text>
        </View>
    </SafeAreaView>
)}

My test file as like follows ,

import React from 'react';
import renderer from 'react-test-renderer';
import BiddingScreen from "../../../src/containers/biddingScreen/BiddingScreen";

jest.mock('@react-native-firebase/auth');

jest.mock("react-native/Libraries/EventEmitter/NativeEventEmitter");


test('renders correctly', () => {
    const tree = renderer.create(< BiddingScreen />).toJSON();
    expect(tree).toMatchSnapshot();
});

When I'm running my test file I got this error,

TypeError: Cannot read property 'params' of undefined

So can anyone help me to solve this problem, Thank you


Solution

  • As long as your components props don't have defaults, you would need to mock those, something like:

    describe('init', () => {
      test('renders correctly', () => {
        const mockedParams = {
          route: { params: { currentBid: 'whatever-id' } },
          navigation: ''
        };
    
        const tree = renderer.create(<BiddingScreen {...mockedParams} />).toJSON();
        expect(tree).toMatchSnapshot();
      });
    });