如何使用react-testing-library检查元素是否以特定排序呈现?

Tal*_*sky 18 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
Run Code Online (Sandbox Code Playgroud)

.toShowBefore()但是,我在 RTL 中找不到类似的函数。测试内容按特定顺序显示的正确方法是什么?

can*_*bax 17

您可以使用compareDocumentPosition

例如

const e1 = getByText('a');
const e2 = getByText('b');
expect(e1.compareDocumentPosition(e2)).toBe(2); 
Run Code Online (Sandbox Code Playgroud)

getByText是从render函数返回的。

  • 如果您期望“a”出现在“b”之前,那么结果应该是“Node.DOCUMENT_POSITION_FOLLOWING”(即“4”) (5认同)
  • 添加 test-id 过于手动并且还会污染代码 (3认同)

Hav*_*uit 4

我不相信 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');
Run Code Online (Sandbox Code Playgroud)