Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing component that uses react-navigation with Jest

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?

like image 265
alex.ac Avatar asked Sep 07 '17 07:09

alex.ac


People also ask

Which method from Jest is used to test React component?

Snapshot testing is a very useful technique to test React component snapshots using the Jest library.

Can I use Cypress with Jest?

You can use Cypress to test anything that runs in a browser, so you can easily implement it on React, Angular, Vue, and so on. Unlike Jest and React-Testing-Library, Cypress doesn't come pre-installed with create-react-app. But we can easily install it with NPM or your package manager of choice.


1 Answers

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();
});
like image 171
quotesBro Avatar answered Nov 10 '22 08:11

quotesBro