@@ -14,11 +14,12 @@ window.fetch = jest.fn(() => Promise.resolve({ ok: true, json }))
1414
1515beforeEach ( abortCtrl . abort . mockClear )
1616beforeEach ( window . fetch . mockClear )
17+ beforeEach ( json . mockClear )
1718afterEach ( cleanup )
1819
1920const Async = ( { children = ( ) => null , ...props } ) => children ( useAsync ( props ) )
20- const Fetch = ( { children = ( ) => null , input, init, ... props } ) =>
21- children ( useFetch ( input , init , props ) )
21+ const Fetch = ( { children = ( ) => null , input, init, options } ) =>
22+ children ( useFetch ( input , init , options ) )
2223
2324describe ( "useAsync" , ( ) => {
2425 describe ( "common" , common ( Async , abortCtrl ) )
@@ -67,9 +68,54 @@ describe("useFetch", () => {
6768 )
6869 } )
6970
71+ test ( "defer=true uses deferFn" , ( ) => {
72+ const component = (
73+ < Fetch input = "/test" options = { { defer : true } } >
74+ { ( { run } ) => < button onClick = { run } > run</ button > }
75+ </ Fetch >
76+ )
77+ const { getByText } = render ( component )
78+ expect ( window . fetch ) . not . toHaveBeenCalled ( )
79+ fireEvent . click ( getByText ( "run" ) )
80+ expect ( window . fetch ) . toHaveBeenCalledWith (
81+ "/test" ,
82+ expect . objectContaining ( { signal : abortCtrl . signal } )
83+ )
84+ } )
85+
86+ test ( "defer=false uses promiseFn" , ( ) => {
87+ render (
88+ < Fetch input = "/test" init = { { method : "POST" } } options = { { defer : false } } >
89+ { ( { run } ) => < button onClick = { run } > run</ button > }
90+ </ Fetch >
91+ )
92+ expect ( window . fetch ) . toHaveBeenCalledWith (
93+ "/test" ,
94+ expect . objectContaining ( { method : "POST" , signal : abortCtrl . signal } )
95+ )
96+ } )
97+
7098 test ( "automatically handles JSON parsing" , async ( ) => {
7199 render ( < Fetch input = "/test" init = { { headers : { accept : "application/json" } } } /> )
72100 await Promise . resolve ( )
73101 expect ( json ) . toHaveBeenCalled ( )
74102 } )
103+
104+ test ( "json=false disables JSON parsing" , async ( ) => {
105+ render (
106+ < Fetch
107+ input = "/test"
108+ init = { { headers : { accept : "application/json" } } }
109+ options = { { json : false } }
110+ />
111+ )
112+ await Promise . resolve ( )
113+ expect ( json ) . not . toHaveBeenCalled ( )
114+ } )
115+
116+ test ( "json=true enables JSON parsing" , async ( ) => {
117+ render ( < Fetch input = "/test" options = { { json : true } } /> )
118+ await Promise . resolve ( )
119+ expect ( json ) . toHaveBeenCalled ( )
120+ } )
75121} )
0 commit comments