如何用玩笑快照测试React组件上的随机映射键

时间:2019-02-08 15:48:30

标签: reactjs testing jestjs snapshot

我有一个React组件,他的代码如下所示:

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>
);

我需要使用“ shallow”和“ toase-to-json”对此组件进行快照测试。测试如下:

  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();
  });

它会生成如下快照:

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>
`;

如您所见,它为每个项目生成一个随机密钥。问题是,如果我再次运行那些测试,它将崩溃,因为它将再次生成与我已经拥有的密钥不同的随机密钥。 你们如何处理这样的案件?

谢谢!

1 个答案:

答案 0 :(得分:0)

进行测试时,请给shortId生成器提供种子。

shortId.seed(1)

如果您先进行种子植入,那么随机引擎应该吐出同样的东西。

https://github.com/dylang/shortid#shortidseedinteger