In my React Testing Library unit test, I am unable to get the Navlink by role.
getByRole('link', { name: 'help' }) - This fails
The Navlink does not have text, rather it has a help icon which seems to be the problem.
The error I recieve is:
TestingLibraryElementError: Unable to find an accessible element with the role "link" and name "help"
Here are the accessible roles:
link:
Name "Home":
<a
class="active"
href="home"
name="home"
/>
Name "About":
<a
class="inactive"
href="/about"
name="about"
/>
Name "": <--- No name for link with icon
<a
class="inactive"
href="/help"
name="help"
/>
My NavBar:
const NavBar = () => {
return (
<>
<div className="navbar">
<ul>
<li>
<NavLink to="home" className={({isActive}) => (isActive ? 'active' : 'inactive')}>Home</NavLink>
</li>
<li>
<NavLink to="about" className={({isActive}) => (isActive ? 'active' : 'inactive')}>About</NavLink>
</li>
<li>
<NavLink to="help" name="help" className={({isActive}) => (isActive ? 'active' : 'inactive')}><FaQuestionCircle size='1.5rem' className="helpicon"/></NavLink>
</li>
</ul>
</div>
</>
);
};
export default NavBar;
The failing unit test:
describe(Navbar, () => {
const mockedNavigation = jest.fn();
it('should navigate to help page', () => {
const { getByRole } = render(<Navbar />, { wrapper: Router });
fireEvent.click(getByRole('link', { name: 'help' }));
expect(mockedNavigation).toHaveBeenCalledWith(
"help",
{
preventScrollReset: undefined,
relative: undefined,
replace: false,
state: undefined,
unstable_viewTransition: undefined
});
});
});
How do I select a Navlink that does not have text, but uses an icon instead?
Maybe I can use classNames ? Add an additional class as well as the active/inactive?
Another method would be easier though and more readable.
Any help appreciated, thanks again!
2
Answers
The link role should technically work, but if you have trouble targeting a component you have a few other options.
Add a
data-testid
attribute to the element and use the*byTestId
query.https://testing-library.com/docs/queries/bytestid
You can also always use querySelector on the rendered
container
.https://testing-library.com/docs/queries/about#manual-queries
A Query similar to
"a[href='/help']"
or"a[href='/help'].inactive"
:Take a look through the About Queries documentation, there may be other options available to you as well depending on implementation or information that you may’ve omitted in your post that we’re unaware of.
The
<NavLink/>
component can’t accept thename
property. If you use TypeScript, you will get a TS-type error:Instead, you can pass a
title
prop to the icon component as the accessible name of the<NavLink/>
. E.g.NavBar.test.tsx
:Test result:
package version: