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?
Snapshot testing is a very useful technique to test React component snapshots using the Jest library.
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.
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();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With