Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write unit test cases for navigation stack in react native using enzyme jest?

I am new to react native and trying to write unit test cases. I am able to write snapshot test cases but not sure how to write unit test cases for navigation stack.

is there any way to write unit test cases for navigation?

navigator.js

import { createStackNavigator } from 'react-navigation-stack';
import { createAppContainer } from 'react-navigation';
import HomeScreen from '../component/HomeComponent/home';
import ThumbnailView from '../component/ThumbnailComponent/thumbnailView';
import AlbumDetailsView from '../component/AlbumDetailsComponent/albumDetailsView';


const MainNavigator = createStackNavigator({
  HomeScreen: { screen: HomeScreen },
  ThumbnailViewScreen: { screen: ThumbnailView },
  AlbumDetailsViewScreen: { screen: AlbumDetailsView },
},
{
  defaultNavigationOptions: {
    headerTintColor: '#fff',
    headerStyle: {
      backgroundColor: '#0c82f3',
    },
    headerTitleStyle: {
      fontWeight: 'bold',
    },
  },
});

const NavigationApp = createAppContainer(MainNavigator);
export default NavigationApp;
like image 698
New iOS Dev Avatar asked Nov 07 '22 09:11

New iOS Dev


1 Answers

You can test navigate function in your components like this:

import HomeScreen from '../component/HomeComponent/home';
import { shallow, ShallowWrapper } from "enzyme";
import React from "react";
import { View } from "react-native";

const createTestProps = (props) => ({
  navigation: {
    navigate: jest.fn()
  },
  ...props
});

describe("HomeScreen", () => {
  describe("rendering", () => {
    let wrapper;
    let props;
    beforeEach(() => {
      props = createTestProps({});
      wrapper = shallow(<HomeScreen {...props} />);
    });

    it("should render a <View /> and go to ThumbnailViewScreen", () => {
      expect(wrapper.find(View)).toHaveLength(1);   // Some other tests
      expect(props.navigation.navigate).toHaveBeenCalledWith('ThumbnailViewScreen');  // What you want
    });
  });
});

HomeScreen.js :

import React, { Component } from "react";
import { Text, View } from "react-native";

export class HomeScreen extends Component {
  componentDidMount = () => {
    this.props.navigation.navigate("ThumbnailViewScreen");
  };

  render() {
    return (
      <View>
        <Text>This is the HomeScreen.</Text>
      </View>
    );
  }
}

export default HomeScreen;

You can find more details here

like image 115
Mohsen Avatar answered Nov 15 '22 12:11

Mohsen