Skip to content

Commit 3804516

Browse files
committed
setup: useApi custom hook
1 parent d8f33b6 commit 3804516

File tree

2 files changed

+45
-1
lines changed

2 files changed

+45
-1
lines changed

src/components/Feed/index.js

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,16 @@ import "./styles.css";
55

66
import fetchData from "../../services/api";
77

8+
export const useApi = url => {
9+
// TODO: loading, error, data loader from API
10+
// TODO: pass the url in so that we call fetchData(url)
11+
return {
12+
loading,
13+
error,
14+
data
15+
};
16+
};
17+
818
export const Feed = () => {
919
const [loading, setLoading] = React.useState(true);
1020
const [error, setError] = React.useState(null);

src/tests/components/Feed.test.js

Lines changed: 35 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
import React from "react";
22
import { render } from "@testing-library/react";
33
import { waitForElementToBeRemoved } from "@testing-library/dom";
4-
import { Feed } from "../../components/Feed";
4+
import { renderHook } from "@testing-library/react-hooks";
5+
import { Feed, useApi } from "../../components/Feed";
56

67
const mockData = [
78
{
@@ -45,3 +46,36 @@ describe("Feed", () => {
4546
expect(feed).toBeDefined();
4647
});
4748
});
49+
50+
// Hook
51+
52+
describe("useApi", () => {
53+
test("should initialize with an error null", async () => {
54+
const { result, waitForNextUpdate } = renderHook(() => useApi());
55+
await waitForNextUpdate();
56+
expect(result.current.error).toBe(null);
57+
});
58+
59+
// generated useEffect async warnings
60+
test("should initialize with loading true", async () => {
61+
const { result } = renderHook(() => useApi());
62+
expect(result.current.loading).toBe(true);
63+
});
64+
65+
test("should change loading to true on update", async () => {
66+
const { result, waitForNextUpdate } = renderHook(() => useApi());
67+
await waitForNextUpdate();
68+
expect(result.current.loading).toBe(false);
69+
});
70+
71+
test("should initialize with data null", () => {
72+
const { result } = renderHook(() => useApi());
73+
expect(result.current.data).toBe(null);
74+
});
75+
76+
test("should return data once api completes", async () => {
77+
const { result, waitForNextUpdate } = renderHook(() => useApi());
78+
await waitForNextUpdate();
79+
expect(result.current.data.length).toBe(1);
80+
});
81+
});

0 commit comments

Comments
 (0)