React redux表单字段数组单元测试失败

时间:2018-05-31 10:06:10

标签: reactjs unit-testing redux-form enzyme

我有一个字段数组件,我有条件地渲染一些组件。该组件如下所示:

export const UttakPeriod = ({
  fields,
  updatePeriode,
  editPeriode,
  cancelEditPeriode,
  isAnyFormOpen,
  isNyPeriodeFormOpen,
  readOnly,
  periods,
  ...other
}) => (
  <div>
    {fields.map((fieldId, index, field) => {
      const period = field.get(index);

      return (
        <div key={fieldId}>
          {other.meta.error && index === 0 ? <AlertStripe type="warning">{other.meta.error}</AlertStripe> : null}
          <Row>
            <Column>
                <UttakPeriodType />
                <UttakPeriodContent />
            </Column>
            {periods.length === fields.length &&
                renderValidationGraphic(periods, index, index === (fields.length - 1))
              }
          </Row>
        </div>
      );
    })}
  <

/div>
);

我正在尝试测试renderValidationGraphic函数呈现的内容,如下所示:

const renderValidationGraphic = (periods, index, isLastIndex) => {
  if (!isLastIndex) {
    const period= periods[index];
    const nextPeriod = periods[index + 1];
    const diff = calcDays(period.tom, nextPeriod .fom, 'YYYY-MM-DD');

    if (moment(period.tom) >= moment(nextPeriod .fom)) {
      return (
        <div className={styles.periodIconWrapper}>
          <Image src={overlapp} alt="Periods overlap" />
        </div>
      );
    }
  }

  return null;
};

我试图像这样测试:

const getMockedFields = (fieldNames, periods) => {
  const field = {
    get: idx => periods[idx],
  };
  return {
    map: callback => fieldNames.map((fieldname, idx) => callback(fieldname, idx, field)),
  };
};

const fieldNames = ['periods[0]', 'periods[1]'];
const periods = [{
  fom: '2017-10-01',
  id: '2017-10-01 | 2017-10-10',
  openForm: false,
  tom: '2017-10-10',
  updated: false,
}, {
  fom: '2017-10-09',
  id: '2017-10-09 | 2017-10-17',
  openForm: true,
  tom: '2017-10-17',
  updated: false,
}];

const updatePeriode = sinon.spy();
const editPeriode = sinon.spy();
const cancelEditPeriode = sinon.spy();
const isAnyFormOpen = sinon.spy();

describe('<UttakPeriod>', () => {
  it('should render image for overlapping periods', () => {
    const wrapper = shallowWithIntl(<UttakPeriod
      fields={getMockedFields(fieldNames, periods)}
      updatePeriode={updatePeriode}
      editPeriode={editPeriode}
      cancelEditPeriode={cancelEditPeriode}
      isAnyFormOpen={isAnyFormOpen}
      periods={periods}
      meta={meta}
      readOnly
    />);

    const image = wrapper.find(Image);
    expect(image).to.have.length(1);
    expect(image.prop('alt')).is.equal('Periods overlap');
  });

它适用于现实生活,如果周期重叠,我会得到图像。函数renderValidationGraphic可以正常工作,可以看到here,但测试由于某种原因没有通过。

  

AssertionError:期望{length:0}的长度为1,但得到0

为什么此测试失败,如何修复此测试以使其有效?

0 个答案:

没有答案