2

TLDR:我如何告诉我的 Enzyme / Jest 测试它应该像在 iOS 上运行一样运行测试?我想测试平台特定的行为

我正在构建一个添加 20 像素高度的自定义状态栏组件,如果它在 iOS 上运行以防止我的内容与状态栏重叠。(是的,我知道React-Navigation 有一个 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 或 0 或 Android。问题是我找不到如何使用 Enzyme / Jest 测试来模拟平台。

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

4

1 回答 1

5

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

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)

于 2018-08-21T12:10:41.133 回答