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>;
}
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"
);
});
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/
);
});
Top comments (0)