验证子组件的prop在酶中是否具有特定功能

时间:2019-01-11 18:46:10

标签: reactjs unit-testing jestjs enzyme

当我在测试中继续引用子组件并且想要检查进入子组件的道具之一是否具有某种功能时,我不断被告知,Jest中未定义子组件,尽管事实是它已导入,并且在组件渲染时并非未定义。该组件的代码如下:

// second

Jest想要测试的未发现行是Dropdown子组件中prop getOptionLabel中的两行。从我无权访问的API导入了Dropdown组件,因此我看不到Dropdown组件的内幕。

在我的Jest文件中(也使用酶),测试如下:

class ActivityItemsDropdown extends React.Component {
  constructor(props) {
    super(props);
    this.state = { id: '' };
  }
  ...(various methods here)...
  render() {
  const {
    // these props are being dispatched from a redux state
    selectedOption,
    selectNewOption,
    onFilterChange,
    loanDates,
    loans,
    intl,
    } = this.props;
  return (
    <div className="dls-accent-gray-03-bg flex flex-align-center">
      <div className="col-md-3 margin-l margin-t pad-0">
        <Dropdown
          id="statements-dropdown"
          options={getOptions(loanDates, loans, intl)}
          value={selectedOption}
          onChange={index => onStatementChange(index,
          loanDates,
          loans,
          selectNewOption,
          onFilterChange)}
          label={intl.formatMessage({ id: 'loanActivityAndHistory.statementDropdown.view' })}
          getOptionLabel={({selectedLabel: label}) => {
          const lines = label.split('-');
          return { firstLine: lines[0], secondLine: lines[1] };
        }}
      />
    </div>
    {selectedOption === CUSTOM
      ? <ActivityItemsDatePicker applyCustomDates={onFilterChange} />
      : ''}
    </div>
    );
   }
  }

测试没有任何问题可以抓住下拉列表,因此它可以模拟更改,但是当我尝试查找具有的道具时会发现下拉列表“ undefined”。

在我的组件文件和测试文件中,我都从正在使用的API导入Dropdown组件(访问ActivityItemsDropdown组件文件中的Dropdown组件没有问题)。

我在Jest中收到的错误是:

const testRecentActivityWhenCurrentStatementPresent = async () => {
  const wrapper = await shallow(<ActivityItemsDropdown
    selectedOption="1"
    selectNewOption={selectNewOption}
    onFilterChange={onFilterChange}
    loanDates={loanDates}
    loans={loans}
    intl={intl}
  />);

  const twoLineLabel = ({selectedLabel: label}) => {
    const lines = label.split('-');
    return { firstLine: lines[0], secondLine: lines[1] };
  }

  const dropdown = wrapper.find('#statements-dropdown');
  expect(dropdown.props().getOptionLabel).to.equal(twoLineLabel);
  dropdown.simulate('change', { value: 'RECENT_ACTIVITY' });
  expect(selectNewOption).toHaveBeenCalledWith({ value: 'RECENT_ACTIVITY' });
  expect(onFilterChange).toHaveBeenCalledWith('Jun 15, 2018', moment().format('MMM DD, YYYY'));
};

很抱歉,这个过程很长,但是我已经玩了两个小时了,这时我不知所措。

1 个答案:

答案 0 :(得分:0)

我不确定您使用的是哪个断言/期望库,但是好像您从Enzyme文档中举了一个例子。

在他们的示例中,酶正在使用Chai expect,而您应该在使用Jest expect

expect(dropdown.props().getOptionLabel).toEqual(twoLineLabel);