How to implement jest unit test with react-navigation

Viewed 1412

I currently working on adding jest unit test for the react-navigation, for example: My StackNavigator

const Nav = StackNavigator({
    Home: {
        screen: Home,
    },

    Second: {
        screen: Second,
    }
});

export default class App extends Component<{}> {
  render() {
    return (
      <Nav/>
    );
  }
}

My Home component

export default class Home extends Component<{}> {

    _goToNextPage = () => {
        this.props.navigation.navigate('Second');
    }

    render() {
        return (
            <View>
                <Text>Home</Text>
                <Button
                    onPress={this._goToNextPage}
                    title="Go to Second Page"
                >Click to next page</Button>
            </View>
    );
    }
}

My Second component export default class Second extends Component<{}> {

render() {
    return (
        <View>
            <Text>Second</Text>
        </View>
    );
}

}

How should I write jest unit test to test "when I click the GoToNextPage button, and the Second Component should be rendered correctly ?"

I do not find any useful info about jest with react-navigation, Any help will be much appreciated!!!

Thanks a lot~

1 Answers

I personally like @testing-library/react for this because of their philosophy around testing from the user perspective. I'd imagine your test would look something like the following:

it('shows the second component when the next button is clicked', async () => {
  // Renders your app
  const { getByText, findByText } = render(<App />);
  // Clicks your button
  fireEvent.click(getByText('Click to next page'));
  // Waits for the 'Second' text to be visible, could be async or sync, in this
  // case I'm using the async expectation style
  await wait(() => expect(getByText('Second')));
});

I would test this in a way that separates the concerns of the click of the button and the validation that it renders properly by simply rendering the second component and checking it against your snapshot.

// inside your second component test - still using testing-library
it('matches the snapshot', () => {
  expect(render(<Second />).container).toMatchSnapshot();
});
Related