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

Viewed 3174

I can find an element by its text and check that it's a link with:

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

How can I check this other element (which I find by text) is not a link?

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

Testing library docs have a priority, and the first query they recommend is the queryByRole, where you can query by a specific role, and also by a name, which is your case.

You can do:

expect(screen.getByRole('link', { name: /this is a link/i })).toBeInTheDocument();

expect(screen.queryByRole('link', { name: /not a link/i })).toBe(null);

Note that you need to do queryBy if the element does not exist, as the getBy query will throw an error and will make your test fail.

Related