测试在循环中显示其他组件的React组件

时间:2017-12-03 12:34:36

标签: javascript reactjs react-native jestjs

我正在开发一个本机应用程序。有一个简单的组件可以获取一个数组,并使用react-native-maps将其显示为地图上的标记。

我正在尝试测试该组件。在测试中,我想检查数组的每个元素是否有标记。

但是,我收到了这个错误:

    console.error node_modules/fbjs/lib/warning.js:33
      Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in.

      Check the render method of `Places`.
          in Places
    console.error node_modules/react-test-renderer/cjs/react-test-renderer.development.js:2053
      The above error occurred in the  component:
          in MapView (created by Places)
          in Places

      Consider adding an error boundary to your tree to customize error handling behavior.
      You can learn more about error boundaries at https://reactjs.org/docs/error-boundaries.html.

  ● shows a marker for each place

    Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in.

    Check the render method of `Places`

这是我的代码

Places.js

export default class Places extends Component<{}> {
  //constructor

  render() {
    return (
      <MapView style={styles.container}
        initialRegion={this.state.initialRegion}
      >
        {this.props.places.map(place => (
          <MapView.Marker
            key={place.id}
            coordinate={{
              latitude: place.location.lat,
              longitude: place.location.lng
            }}
            title={place.name}
          />
        ))}
      </MapView >
    );
  }
}

__测试__ / Places.js

import 'react-native';
import React from 'react';
import Places from '../../src/places/Places'

import renderer from 'react-test-renderer';

jest.mock('react-native-maps', () => 'MapView');

it('shows a marker for each place', () => {
  const places = [
    { id: 1, name: 'test', location: { lat: 1, lng: 2 } }
  ];

  const testee = renderer.create(
    <Places places={places} />
  );
  
  //not even having any expect statements yet
});

我非常确定我做的事情很傻,但我找不到测试这些组件的互联网示例。

1 个答案:

答案 0 :(得分:0)

我使用enzyme

解决了这个问题

&#13;
&#13;
it('shows a place component for each place', () => {
  const testee = shallow(
    <Places places={places} />
  );

  const placeComponents = testee.find('Place');

  expect(placeComponents.length).toEqual(places.length);

  placeComponents.forEach((placeComponent, index) => {
        expect(placeComponent.prop('place')).toEqual(places[index]);
  });
});
&#13;
&#13;
&#13;