测试元素在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。

最新更新