vendredi 8 février 2019

How to snapshot test random map keys on React components with jest

I have a React component that his code looks like that:

const TakeADecision = ({
  decisions,
  decisionTaken,
  preDecisionsSection,
  takeDecision,
  title,
  titlePrefix,
}) => (

  <div className="take-a-decision">

    <Title text={title} prefix={titlePrefix} />

    { preDecisionsSection }

    <SelectionButtonGroup>
      {
        decisions.map((decisionItem, i) => (
          <SelectionButton
            selected={decisionItem.statusCode === decisionTaken}
            action={takeDecision}
            key={shortId.generate()}
            index={i}
            alt={decisionItem.label}
          >
            {decisionItem.label}
          </SelectionButton>
        ))
      }

    </SelectionButtonGroup>
  </div>
);

I need to snapshot test this component with shallow and enzyme-to-json. The test looks like:

  const props = {
    title: 'This is the title',
    titlePrefix: '0',
    preDecisionsSection: 'This should be the preDecisionsSection',
    decisions: [
      { label: 'One', statusCode: 'one' },
      { label: 'Two', statusCode: 'two' },
    ],
    choice: 'This is the choice text',
    decisionTaken: 'one',
    takeDecision: jest.fn(),
  }

  it('renders correctly based on the given decisions', () => {
    const wrapper = shallow(<TakeDecisionStep {...props} />);
    expect(toJson(wrapper)).toMatchSnapshot();
  });

It results in a snapshot like this:

exports[`TakeDecisionStep component renders correctly based on the given decisions 1`] = `
<div
  className="take-decision-step"
>
  <Title
    prefix="0"
    text="This is the title"
  />
  This should be the preDecisionsSection
  <Connect(SelectionButtonGroup)>
    <SelectionButton
      action={[Function]}
      alt="One"
      image=""
      index={0}
      key="MKSGeZOIs"
      selected={true}
    >
      One
    </SelectionButton>
    <SelectionButton
      action={[Function]}
      alt="Two"
      image=""
      index={1}
      key="fFzPmlHg9m"
      selected={false}
    >
      Two
    </SelectionButton>
  </Connect(SelectionButtonGroup)>
</div>
`;

As you can see, it generates a random key per item. The problem is if I run those tests again, it will crash since it will generate a random key again different to the one I already had. How do you guys deal with cases like that?

Thanks!

Aucun commentaire:

Enregistrer un commentaire