首页 > 解决方案 > React Native + Jest + Enzyme:为什么 Enzyme 不能识别某些组件?

问题描述

我目前正在学习使用 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将它的内部组件包装在 a 中<View />

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

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

但不知何故,这个测试失败了。如果我使用相同的结构来测试<TextInput ... />它是否有效。

我错过了什么?

标签: reactjsunit-testingreact-nativejestjsenzyme

解决方案


问题在于您正在测试的不同项目是如何导入的。TextInput 之所以有效,是因为它是一个命名引用。在 Enzyme 中,您使用如下字符串测试命名引用:wrapper.find("myComponent")

而您尝试测试的组件是直接引用,因此您可以在 Enzyme 中测试它们而不带引号,如下所示:wrapper.find(myComponent).


推荐阅读