检查反应测试库的getByText的结果的HTML元素类型? [英] Check HTML element type for result of React Testing Library's getByText?
本文介绍了检查反应测试库的getByText的结果的HTML元素类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我可以根据元素的文本查找元素,并检查它是否为以下链接:
const Link = Parent.getByText('This is a link', { exact: false });
expect(Link).toHaveAttribute('href', 'www.somewhere.com');
如何检查其他元素(我通过文本找到的)不是链接?
const NotALink = Parent.getByText('Not a link', { exact: false });
推荐答案
测试库文档有一个priority,它们建议的第一个查询是queryByRole
,其中you can query by a specific role,还有一个名称,这是您的情况。
您可以:
expect(screen.getByRole('link', { name: /this is a link/i })).toBeInTheDocument();
expect(screen.queryByRole('link', { name: /not a link/i })).toBe(null);
请注意,如果元素不存在,则需要执行queryBy,因为getBy查询将引发错误并使您的测试失败。
这篇关于检查反应测试库的getByText的结果的HTML元素类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文