如何快照上反应以开玩笑成分测试随机地图键

问题描述 投票:0回答:1

我有自己的代码看起来像一个阵营组成:

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

我需要快照测试浅和酶对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>
`;

正如你所看到的,它产生每件随机密钥。问题是,如果我再次运行这些测试,它会崩溃,因为它会产生一个随机密钥到一个我已经再次不同。你们如何处理这样的情况?

谢谢!

reactjs testing jestjs snapshot
1个回答
0
投票

当你测试,给短ID发生器的种子。

shortId.seed(1)

随机引擎应该吐出同样的事情,如果你第一种子吧。

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

© www.soinside.com 2019 - 2024. All rights reserved.