使用 Jest 的 react-navigation 测试组件 [英] Testing component that uses react-navigation with Jest

查看:27
本文介绍了使用 Jest 的 react-navigation 测试组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个也使用 Redux 的 React Native 应用程序,我想用 Jest 编写测试.我无法模拟 react-navigation 添加的导航"道具.

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.

这是我的组件:

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);

Loading 组件作为屏幕添加到 DrawerNavigator.

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

这是测试:

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?

推荐答案

尝试直接通过props传递navigation:

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();
});

这篇关于使用 Jest 的 react-navigation 测试组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆