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

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

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

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

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

javascript jest react-testing-library
1个回答
0
投票

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

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