How to Check if a Link Has a Specific Href Using React Testing Library
— testing, jest, react testing library — 1 min read
React Testing Library (RTL) is a popular testing library used for testing React components. It provides a simple and intuitive API for interacting with and testing UI components. To check if a link has a specific href using RTL, we can use the getByRole
query and the toHaveAttribute
matcher.
Here's an example code snippet that demonstrates how to do this:
import { render } from "@testing-library/react";import React from "react";import App from "./App";
test("renders a link with specific href", () => { const { getByRole } = render(<App />); const link = getByRole("link", { name: "Example Link" }); expect(link).toHaveAttribute("href", "https://example.com");});
In this example, we first render the App
component using the render
method provided by RTL. We then use the getByRole
query to retrieve the link element by its role and accessible name or description. The toHaveAttribute
matcher is then used to assert that the link has the expected href
attribute value.
This approach allows us to easily and effectively test whether a link has a specific href
attribute value and helps ensure that links in our UI components are correctly configured and lead to the expected destinations.