React + Jest检查组件包含另一个组件

时间:2017-11-02 10:10:23

标签: reactjs enzyme jest

我的DetailPanel组件包含Detail组件与title道具。

import React from 'react';
import Detail from './Detail';
import InfoTable from './InfoTable';
import EdgeIcon from './EdgeIcon';
import styles from './DetailsPanel.css';

export default class DetailsPanel extends React.PureComponent {

  renderTitle() {
    const { selectedEdge } = this.props;

    if (selectedEdge) {
      const sourceNode = 'sourceNode'
      const targetNode = 'targetNode'

      return (
        <span>
          {sourceNode}
          <EdgeIcon className={styles.arrowIcon} />
          {targetNode}
        </span>
      );
    }

    return 'default title';
  }

  render() {
    return (
      <Detail title={this.renderTitle()} />
    );
  }
}

如果selectedEdgetrue,我需要检查明细标题是否包含EdgeIcon组件

test('Detail should contain EdgeIcon if there is selected edge', () => {
  const selectedEdge = { source: 1, target: 2 };
  const detailsPanel = shallow(
    <DetailsPanel
      {...props}
      selectedEdge={selectedEdge}
    />);
  expect(detailsPanel.contains('EdgeIcon')).toBeTruthy();
});

但测试失败,因为detailsPanel返回false

2 个答案:

答案 0 :(得分:0)

如果您想检查深儿,可以尝试使用mount代替shallow。例如:

test('Detail should contain EdgeIcon if there is selected edge', () => {
  const selectedEdge = { source: 1, target: 2 };
  const detailsPanel = mount(
    <DetailsPanel
      {...props}
      selectedEdge={selectedEdge}
    />);
  expect(detailsPanel.contains('EdgeIcon')).toBeTruthy();
});

答案 1 :(得分:0)

首先,在测试组件时,您不应该测试其子组件。每个孩子都应该有自己的考试。

但如果你真的需要调查你的组件的孩子,请使用mount代替shallow

参考:http://airbnb.io/enzyme/docs/api/ReactWrapper/mount.html