Skip to content

Commit 009891c

Browse files
committed
Cover Link component with specs.
1 parent 7219553 commit 009891c

File tree

1 file changed

+73
-0
lines changed

1 file changed

+73
-0
lines changed

test/link.test.js

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
import React from "react";
2+
import { render, cleanup, fireEvent } from "react-testing-library";
3+
4+
import { Link } from "../index.js";
5+
6+
afterEach(cleanup);
7+
8+
it("renders a link with proper attributes", () => {
9+
const { container } = render(
10+
<Link href="/about">
11+
<a className="link--active">Click Me</a>
12+
</Link>
13+
);
14+
15+
const link = container.firstChild;
16+
17+
expect(link.tagName).toBe("A");
18+
expect(link.className).toBe("link--active");
19+
expect(link.getAttribute("href")).toBe("/about");
20+
expect(link.textContent).toBe("Click Me");
21+
});
22+
23+
it("wraps children in an <a /> if needed", () => {
24+
const { container } = render(<Link href="/about">Testing</Link>);
25+
const link = container.firstChild;
26+
27+
expect(link.tagName).toBe("A");
28+
expect(link.textContent).toBe("Testing");
29+
});
30+
31+
it("works for any other elements as well", () => {
32+
const { container } = render(
33+
<Link href="/about">
34+
<div className="link--wannabe">Click Me</div>
35+
</Link>
36+
);
37+
38+
const link = container.firstChild;
39+
40+
expect(link.tagName).toBe("DIV");
41+
expect(link.className).toBe("link--wannabe");
42+
expect(link.textContent).toBe("Click Me");
43+
});
44+
45+
it("supports `to` prop as an alias to `href`", () => {
46+
const { container } = render(<Link to="/about">Hello</Link>);
47+
const link = container.firstChild;
48+
49+
expect(link.getAttribute("href")).toBe("/about");
50+
});
51+
52+
it("performs a navigation when the link is clicked", () => {
53+
const { container, getByTestId } = render(
54+
<Link href="/goo-baz">
55+
<a data-testid="link" />
56+
</Link>
57+
);
58+
fireEvent.click(getByTestId("link"));
59+
expect(location.pathname).toBe("/goo-baz");
60+
});
61+
62+
it("accepts an `onClick` prop, fired after the navigation", () => {
63+
const clickHandler = jest.fn();
64+
65+
const { container, getByTestId } = render(
66+
<Link href="/" onClick={clickHandler}>
67+
<a data-testid="link" />
68+
</Link>
69+
);
70+
71+
fireEvent.click(getByTestId("link"));
72+
expect(clickHandler).toHaveBeenCalledTimes(1);
73+
});

0 commit comments

Comments
 (0)