首页 > 解决方案 > React redux 表单字段数组单元测试失败

问题描述

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

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工作,可以在此处看到,但由于某种原因测试未通过。

AssertionError:预期 { 长度:0 } 的长度为 1 但得到 0

那么为什么这个测试会失败,我该如何修复这个测试以使其正常工作?

标签: reactjsunit-testingredux-formenzyme

解决方案


推荐阅读