测试一个元素在 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();

});


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


白衣非少年
浏览 135回答 1
1回答

慕工程0101907

考虑使用 getAllBy(点击后)而不是 getBy。这可以生成一个包含所有找到的元素的数组,您可以期望()它的总长度为 2。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript