gpt4 book ai didi

react-native - 如何使用 enzyme Jest 为 React Native 中的导航堆栈编写单元测试用例?

转载 作者:行者123 更新时间:2023-12-03 17:26:20 24 4
gpt4 key购买 nike

我是 native react 的新手并尝试编写单元测试用例。我能够编写快照测试用例,但不确定如何为导航堆栈编写单元测试用例。

有没有办法为导航编写单元测试用例?

导航器.js

import { createStackNavigator } from 'react-navigation-stack';
import { createAppContainer } from 'react-navigation';
import HomeScreen from '../component/HomeComponent/home';
import ThumbnailView from '../component/ThumbnailComponent/thumbnailView';
import AlbumDetailsView from '../component/AlbumDetailsComponent/albumDetailsView';


const MainNavigator = createStackNavigator({
HomeScreen: { screen: HomeScreen },
ThumbnailViewScreen: { screen: ThumbnailView },
AlbumDetailsViewScreen: { screen: AlbumDetailsView },
},
{
defaultNavigationOptions: {
headerTintColor: '#fff',
headerStyle: {
backgroundColor: '#0c82f3',
},
headerTitleStyle: {
fontWeight: 'bold',
},
},
});

const NavigationApp = createAppContainer(MainNavigator);
export default NavigationApp;

最佳答案

您可以测试 navigate像这样在您的组件中运行:

import HomeScreen from '../component/HomeComponent/home';
import { shallow, ShallowWrapper } from "enzyme";
import React from "react";
import { View } from "react-native";

const createTestProps = (props) => ({
navigation: {
navigate: jest.fn()
},
...props
});

describe("HomeScreen", () => {
describe("rendering", () => {
let wrapper;
let props;
beforeEach(() => {
props = createTestProps({});
wrapper = shallow(<HomeScreen {...props} />);
});

it("should render a <View /> and go to ThumbnailViewScreen", () => {
expect(wrapper.find(View)).toHaveLength(1); // Some other tests
expect(props.navigation.navigate).toHaveBeenCalledWith('ThumbnailViewScreen'); // What you want
});
});
});

主屏幕.js :
import React, { Component } from "react";
import { Text, View } from "react-native";

export class HomeScreen extends Component {
componentDidMount = () => {
this.props.navigation.navigate("ThumbnailViewScreen");
};

render() {
return (
<View>
<Text>This is the HomeScreen.</Text>
</View>
);
}
}

export default HomeScreen;

您可以找到更多详情 here

关于react-native - 如何使用 enzyme Jest 为 React Native 中的导航堆栈编写单元测试用例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60501062/

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