检查 HTML 元素类型以获得 React 测试库 getByText 的结果?

Check HTML element type for result of React Testing Library's getByText?

我可以通过其文本找到一个元素并检查它是否是一个 link 具有:

const Link = Parent.getByText('This is a link', { exact: false });
expect(Link).toHaveAttribute('href', 'www.somewhere.com');

我如何检查这个其他元素(我通过文本找到的)不是 link?

const NotALink = Parent.getByText('Not a link', { exact: false });

测试库文档有一个 priority, and the first query they recommend is the queryByRole, where 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 查询会抛出错误并使您的测试失败。