Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit3804516

Browse files
committed
setup: useApi custom hook
1 parentd8f33b6 commit3804516

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
importfetchDatafrom"../../services/api";
77

8+
exportconstuseApi=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
exportconstFeed=()=>{
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
importReactfrom"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
constmockData=[
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+
awaitwaitForNextUpdate();
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+
awaitwaitForNextUpdate();
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+
awaitwaitForNextUpdate();
79+
expect(result.current.data.length).toBe(1);
80+
});
81+
});

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp