gpt4 book ai didi

react-native - 使用 Jest 的 react-navigation 测试组件

转载 作者:行者123 更新时间:2023-12-03 14:44:24 25 4
gpt4 key购买 nike

我正在开发一个也使用 Redux 的 React Native 应用程序,我想用 Jest 编写测试。我无法模拟 react 导航添加的“导航” Prop 。

这是我的组件:

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。

这是测试:

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

});
});

当我运行测试时,我收到以下错误:

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)

关于如何模拟导航属性的任何想法?

最佳答案

尝试通过navigation直接通过 Prop :

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

关于react-native - 使用 Jest 的 react-navigation 测试组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46090713/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com