DEV Community

Wilberto Morales
Wilberto Morales

Posted on • Originally published at wilbertom.com

React Testing Library - Testing a Node Attribute

You can test HTML node attributes with the toHaveAttribute matcher. When you need more than an equality check, though, you can use getAttribute.

For example, here is a component that has a mailto link. Let's test the subject and recipient.

import React from "react";

export function Component() {
  return <a href="mailto:example@example.com?subject=Hello">Send</a>;
}
Enter fullscreen mode Exit fullscreen mode

You could write one test:

import React from "react";
import { Component } from "./component.jsx";
import { render } from "@testing-library/react";
import "@testing-library/jest-dom/extend-expect";

it("has a subject and correct recipient", () => {
  const component = <Component />;
  const { getByText } = render(component);

  expect(getByText("Send")).toHaveAttribute(
    "href",
    "mailto:example@example.com?subject=Hello"
  );
});
Enter fullscreen mode Exit fullscreen mode

This test case is testing two things at once though, the "and" in the test name gives it
away.

Lets test each idea seperately:

import React from "react";
import { Component } from "./component.jsx";
import { render } from "@testing-library/react";

it("has a subject", () => {
  const component = <Component />;
  const { getByText } = render(component);

  expect(getByText("Send").getAttribute("href")).toMatch(
    /subject=Hello/
  );
});

it("emails the example email address", () => {
  const component = <Component />;
  const { getByText } = render(component);

  expect(getByText("Send").getAttribute("href")).toMatch(
    /mailto:example@example.com/
  );
});
Enter fullscreen mode Exit fullscreen mode

Top comments (0)