首页 > 解决方案 > 如何使用 react-testing-library 检查元素是否以特定排序呈现?

问题描述

通过它以用户为中心的方法,我对 RTL 的理解是测试元素的排序应该看起来像这样。

const foo = queryByText('foo');
const bar = queryByText('bar');
expect(foo).toBeInTheDocument();
expect(bar).toBeInTheDocument();
expect(foo).toShowBefore(bar); // THIS IS MY PSEUDOCODE

.toShowBefore()但是,我在 RTL 中找不到一个或等效的函数。测试内容以特定顺序显示的正确方法是什么?

标签: react-testing-library

解决方案


我不相信 React 测试库有一种惯用的方式来做到这一点。但是,如果您可以解析 DOM,那么您应该能够获取各种元素的 textContent 并对其进行断言。

const select = screen.getByTestId('select');
const children = select.children;

expect(children.item(0)?.textContent).toEqual('Interface A');
expect(children.item(1)?.textContent).toEqual('Interface B');
expect(children.item(2)?.textContent).toEqual('Interface C');

推荐阅读