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

标签 react-native unit-testing jestjs enzyme

我是 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/

相关文章:

node.js - 为什么客户端的 socket.disconnect() 不会在服务器上触发断开连接事件?

java - EasyMock.expect(...).times(...) 与多次使用 EasyMock.expect(...) 之间的区别?

ios - 单元测试文件是否会增加已发布版本的应用程序大小

reactjs - react storybook jest snapshots 导致错误 Cannot find module '../../package' from 'node.js'

javascript - 当我单击 native react 按钮时如何显示或切换文本?

react-native - 已弃用的 Gradle 功能不兼容

c - 如何在 C 中集成测试网络应用程序

react-native - 测试 Pressable 的按下状态

unit-testing - react-native-firebase-messaging 开 Jest

react-native - 如何从 headlessTask react-native 打开屏幕