20

I'm working on a React Native application that also use Redux and I want to write tests with Jest. I'm not able to mock the "navigation" prop that is added by react-navigation.

Here is my component:

import React from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { Text, View } from 'react-native';

const Loading = (props) => {
  if (props.rehydrated === true) {
    const { navigate } = props.navigation;
    navigate('Main');
  }
  return (
    <View>
      <Text>Loading...</Text>
    </View>
  );
};

Loading.propTypes = {
  rehydrated: PropTypes.bool.isRequired,
  navigation: PropTypes.shape({
    navigate: PropTypes.func.isRequired,
  }).isRequired,
};

const mapStateToProps = state => ({
  rehydrated: state.rehydrated,
});

export default connect(mapStateToProps)(Loading);

The Loading component is added as a screen to a DrawerNavigator.

And here is the test:

import React from 'react';
import renderer from 'react-test-renderer';
import mockStore from 'redux-mock-store';

import Loading from '../';

describe('Loading screen', () => {

  it('should display loading text if not rehydrated', () => {
    const store = mockStore({
      rehydrated: false,
      navigation: { navigate: jest.fn() },
    });

    expect(renderer.create(<Loading store={store} />)).toMatchSnapshot();

  });
});

When I run the test, I get the following error:

Warning: Failed prop type: The prop `navigation` is marked as required in `Loading`, but its value is `undefined`.
          in Loading (created by Connect(Loading))
          in Connect(Loading)

Any idea on how to mock the navigation property?

1 Answer 1

38

Try to pass navigation directly via props:

it('should display loading text if not rehydrated', () => {
  const store = mockStore({
    rehydrated: false,
  });
  const navigation = { navigate: jest.fn() };

  expect(renderer.create(<Loading store={store} navigation={navigation} />)).toMatchSnapshot();
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.