React Native + Jest + Enzyme:为什么酶不能识别某些成分?

时间:2018-07-08 17:55:29

标签: reactjs unit-testing react-native jestjs enzyme

我目前正在使用酶学习单元测试。

似乎有一种怪异的行为:酶似乎随机地不能识别某些成分。让我给你举个例子:

这是我的SafeContainer组件:

import React from "react";
import { SafeAreaView } from "react-native";
import { PropTypes } from "prop-types";

import styles from "./styles";

const SafeContainer = ({ children }) => {
  return <SafeAreaView style={styles.container}>{children}</SafeAreaView>;
};

SafeContainer.propTypes = {
  children: PropTypes.any
};

export default SafeContainer;

这是我的AuthInput组件:

import React, { PureComponent } from "react";
import { Text, TextInput, View } from "react-native";
import PropTypes from "prop-types";

import colors from "../../config/constants/themes";
import styles from "./styles";

class AuthInput extends PureComponent {
  handleChange = value => {
    const { onChange, name } = this.props;
    onChange(name, value);
  };

  handleTouch = () => {
    const { onTouch, name } = this.props;
    onTouch(name);
  };

  render() {
    const { placeholder, error } = this.props;
    return (
      <View>
        <TextInput
          autoCapitalize="none"
          autoCorrect={false}
          style={[styles.input, error ? styles.errorInput : null]}
          placeholder={placeholder}
          placeholderTextColor={colors.$lightGrey}
          onChangeText={this.handleChange}
          underlineColorAndroid="transparent"
          onBlur={this.handleTouch}
          {...this.props}
        />
        {error && <Text style={styles.errorText}>{error}</Text>}
      </View>
    );
  }
}

AuthInput.propTypes = {
  placeholder: PropTypes.string,
  name: PropTypes.string,
  error: PropTypes.string,
  onChange: PropTypes.func,
  onTouch: PropTypes.func
};

export default AuthInput;

现在这是我测试SafeContainer使用SafeAreaView的方法:

import React from "react";
import { shallow } from "enzyme";
import SafeContainer from "./SafeContainer";

describe("SafeContainer", () => {
  describe("rendering", () => {
    let wrapper;
    beforeEach(() => {
      wrapper = shallow(<SafeContainer />);
    });

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

我尝试使用相同的方法来测试AuthInput将其内部组件包装在<View />中:

describe("AuthInput", () => {
  describe("rendering", () => {
    let wrapper;
    beforeEach(() => {
      wrapper = shallow(<AuthInput />);
    });

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

但是以某种方式该测试失败。如果我使用相同的结构来测试<TextInput ... />,那么它将起作用。

我想念什么?

1 个答案:

答案 0 :(得分:3)

问题在于如何导入要测试的不同项目。 TextInput之所以起作用,是因为它是一个命名参考。在“酶”中,您使用如下字符串测试“命名引用”:wrapper.find("myComponent")

您要测试的组件是直接引用,因此您可以在酶中测试它们而不使用引号,例如:wrapper.find(myComponent)