【问题标题】:How do I use Jest to test that one text element comes before another?如何使用 Jest 测试一个文本元素是否在另一个之前?
【发布时间】:2022-08-15 22:27:25
【问题描述】:
我有一个要在我的 React 应用程序中呈现的列表,我需要测试我是否按字母顺序列出了列表项。
最初我尝试通过以这种方式查询文档来测试它:
const a = getByText(\"a_item\");
const el = a.parentElement?.parentElement?.nextSibling?.firstChild?.textContent;
expect(el).toEqual(\"b_item\");
但事实证明这很脆弱。我不想测试每个项目的 HTML 结构。我只想测试列表是否按字母顺序排列。
如何在不依赖于列表当前 HTML 结构的情况下测试列表是否按字母顺序排列?
标签:
jestjs
react-testing-library
【解决方案1】:
使用 String.search 在文档的 HTML 中查找字符串的索引,然后断言索引的顺序正确:
it("lists items alphabetically", async () => {
loadItems([
"b_item",
"a_item",
]);
await render(<App/>);
await waitFor(() => {
const html = document.body.innerHTML;
const a = html.search("a_item");
const b = html.search("b_item");
expect(a).toBeLessThan(b);
});
});
请注意,这可能并不理想,因为它直接访问 dom,这在使用 React 测试库时不被认为是最佳实践。我没有对此进行测试,但使用带有内置 React 测试库查询方法的正则表达式匹配器可能会更好:
it("lists items alphabetically", async () => {
loadItems([
"b_item",
"a_item",
]);
await render(<App/>);
expect(await screen.findByText(/a_item.+b_item/)).toBeInTheDocument();
});