DEV Community

loading...

React Testing Library - Testing a Node Attribute

wilbertom profile image Wilberto Morales Originally published at wilbertom.com ・1 min read

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

Discussion (0)

pic
Editor guide