测试一个元素在 Jest/RTL 中只存在一次

Test for an element to exist only once in Jest/RTL

我正在测试一个组件,您可以通过按“+”图标添加子组件。

呈现的 HTML 位于以下行中的某处:

<div>
  <div>
    <div>
      From <input type="text" />
    </div>
    <div>
      To <input type="text" />
    </div>
    <div>+</div>
  </div>
</div>

所以在初始测试中,我测试了文本是否存在:

// test setup

test('From and to occur only once', () => {
  const { getByText } = setup();

  expect(getByText('From')).toBeInTheDocument();
  expect(getByText('To')).toBeInTheDocument();
});

一切正常。但我想确保最初 内容只显示一次

所以我的下一个测试将是:

// test setup

test('When add button is clicked there From and To exist two times', () => {
  const { getByText } = setup();
  const addButton = getByText("+")

  // first row
  expect(getByText('From')).toBeInTheDocument();
  expect(getByText('To')).toBeInTheDocument();

  fireEvent.click(addButton);

  // second row
  expect(getByText('From')).toBeInTheDocument();
  expect(getByText('To')).toBeInTheDocument();
});

如何区分元素出现的第一次和第二次?

考虑使用 getAllBy(点击后)而不是 getBy。这可以生成一个包含所有找到的元素的数组,你可以期望()它的总长度为 2.