React-Native + Enzyme + Jest:如何测试平台的特定行为?

时间:2018-08-20 08:57:42

标签: react-native jestjs enzyme platform platform-specific

TLDR:我如何告诉我的Enzyme / Jest测试应该像在iOS上一样运行测试?我想测试platform specific behaviour

我正在构建一个自定义状态栏组件,如果该组件在iOS上运行时会增加20像素的高度,以防止我的内容与状态栏重叠。 (是的,我知道React-Navigation has a SafeAreaView,但这仅适用于iPhone X,不适用于iPad。)

这是我的组成部分:

import React from "react";
import { StatusBar as ReactNativeStatusBar, View } from "react-native";

import styles from "./styles";

const StatusBar = ({ props }) => (
  <View style={styles.container}>
    <ReactNativeStatusBar {...props} />
  </View>
);

export default StatusBar;

这是styles.js文件:

import { StyleSheet, Platform } from "react-native";

const height = Platform.OS === "ios" ? 20 : 0;

const styles = StyleSheet.create({
  container: {
    height: height
  }
});

export default styles;

这是到目前为止的测试:

import React from "react";
import { shallow } from "enzyme";
import { View } from "react-native";

import StatusBar from "./StatusBar";

const createTestProps = props => ({
  ...props
});

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

    it("should render a <View />", () => {
      expect(wrapper.find(View)).toHaveLength(1);
    });

    it("should give the <View /> the container style", () => {
      expect(wrapper.find(View)).toHaveLength(1);
    });

    it("should render a <StatusBar />", () => {
      expect(wrapper.find("StatusBar")).toHaveLength(1);
    });
  });
});

现在我想做的是再添加两个描述区域,以明确测试高度在iOS或20或Android上是否为20。问题是我找不到如何用酶/ Jest测试来模拟平台。

那么我如何告诉我的测试套件它应该为相应平台运行代码?

1 个答案:

答案 0 :(得分:3)

您可以覆盖RN Platform对象,并对每个平台执行不同的测试。这是一个测试文件的示例:

describe('tests', () => {

    let Platform;
    beforeEach(() => {
        Platform = require('react-native').Platform;
    });

    describe('ios tests', () => {
        beforeEach(() => {
            Platform.OS = 'ios';
        });

        it('should test something on iOS', () => {

        });
    });

    describe('android tests', () => {
        beforeEach(() => {
            Platform.OS = 'android';
        });

        it('should test something on Android', () => {

        });
    });

});

顺便说一句,无论是否有测试问题,将iOS上的状态栏高度设置为20都是错误的,因为在不同的设备(例如iPhone X)上,状态栏的高度可能不同