This repository has been archived by the owner on Mar 12, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7
/
LikeButton.test.tsx
81 lines (70 loc) · 2.38 KB
/
LikeButton.test.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import { render, waitFor, screen, fireEvent } from "@testing-library/react";
import { useLoaderData } from "@remix-run/react";
import { createRemixStub } from "remix-stubs";
import { LikeButton } from "./LikeButton";
// Example implementation of Ryan Florence's tests from https://github.com/remix-run/remix/discussions/2481
describe("LikeButton", () => {
// set up a fake "database" record again
let fakePost = { id: "123", title: "Fake Post", liked: false };
// Make the stub
let RemixStub = createRemixStub([
{
path: "/post/:postId",
loader: () => fakePost,
element: <TestSubject />,
},
{
path: "/post/:postId/like",
action: async ({ request }) => {
let formData = await request.formData();
fakePost.liked = JSON.parse(formData.get("liked") as string);
return null;
},
},
]);
// Now we're testing the component how it's more likely to be used:
function TestSubject() {
let post = useLoaderData();
return (
<LikeButton
liked={post.liked}
label={post.liked ? `Unlike ${post.title}` : `Like ${post.title}`}
action={`/post/${post.id}/like`}
/>
);
}
afterEach(() => {
// reset the fake record
fakePost.liked = false;
});
it("renders an empty heart initially", async () => {
render(
<RemixStub
initialEntries={["/post/123"]}
initialLoaderData={{ "/post/:postId": fakePost }}
/>
);
await waitFor(() => screen.getByRole("button"));
expect(screen.getByRole("button").innerHTML).toMatch("♡");
expect(screen.getByLabelText("Like Fake Post")).toBeDefined();
});
// In this test we no longer need to mock useFetcher return values, the test
// also no longer has to know the implementation details of the spelling of
// "liked" in the formData
it("optimistically renders the heart", async () => {
render(
<RemixStub
initialEntries={["/post/123"]}
initialLoaderData={{ "/post/:postId": fakePost }}
/>
);
fireEvent.click(screen.getByRole("button"));
await waitFor(() => screen.getByText("♥"));
// assert it's optimistic, our action will not have changed this yet
expect(fakePost.liked).toBe(false);
// wait for the action
await waitFor(() => fakePost.liked === true);
// expect to still see the heart
expect(screen.getByText("♥")).toBeDefined();
});
});