@@ -2,13 +2,16 @@ import { beforeEach, afterEach, describe, test, expect } from 'vitest'
22import { api , PlexusApi } from '@plexusjs/api'
33// only imported here to make sure it works in testing environment (node), not needed by user
44import 'isomorphic-fetch'
5+ import { PlexusError } from '@plexusjs/utils'
56
67// if(globalThis.fetch === undefined) globalThis.fetch = fetch as any as (input: RequestInfo, init?: RequestInit) => Promise<Response>;
78
89let myApi : PlexusApi
910
1011beforeEach ( ( ) => {
11- myApi = api ( )
12+ myApi = api ( '' , {
13+ abortOnTimeout : true ,
14+ } )
1215} )
1316describe ( 'Testing Api Function' , ( ) => {
1417 test ( 'Send a get request to google' , async ( ) => {
@@ -87,7 +90,55 @@ describe('Testing Api Function', () => {
8790 apiUsingOnResponse . post ( 'https://google.com/this/url/doesnt/exist' )
8891 ) . rejects . toThrow ( )
8992 } )
90- } )
93+
94+ test ( 'can set a timeout with abort' , async ( ) => {
95+ // const value = state(1)
96+ const apiUsingOnResponse = api ( '' , {
97+ timeout : 1000 ,
98+ throws : true ,
99+ abortOnTimeout : true ,
100+ } )
101+
102+ apiUsingOnResponse . options ( {
103+ headers : {
104+ custom : 'header' ,
105+ } ,
106+ } )
107+ // console.log(myApi.config)
108+ expect ( apiUsingOnResponse . config ) . toBeDefined ( )
109+ expect ( apiUsingOnResponse . config . headers ) . toBeDefined ( )
110+ expect ( apiUsingOnResponse . config . headers [ 'custom' ] ) . toBe ( 'header' )
111+
112+ let errorOccurred = false
113+
114+ try {
115+ await apiUsingOnResponse . post ( 'http://httpstat.us/526?sleep=2800' )
116+ } catch ( error ) {
117+ console . log ( error )
118+ errorOccurred = true
119+ }
120+ expect ( errorOccurred ) . toBe ( true )
121+
122+ // Wait for the sleep duration of the request endpoint
123+ await new Promise ( ( resolve ) => setTimeout ( resolve , 3000 ) )
124+
125+ // Check if a second error is thrown
126+ errorOccurred = false
127+
128+ try {
129+ await apiUsingOnResponse . post ( 'http://httpstat.us/526?sleep=2800' )
130+ } catch ( error ) {
131+ console . log ( error )
132+ if ( error instanceof PlexusError ) {
133+ // if it's a PlexusError, it means this is the timeout error
134+ return
135+ }
136+ errorOccurred = true
137+ }
138+
139+ expect ( errorOccurred ) . toBe ( false )
140+ } )
141+ } , 10000 )
91142describe ( "Test the API's baseURL capabilities" , ( ) => {
92143 const myApi2 = api ( 'https://google.com' ) . setHeaders ( {
93144 'Content-Type' : 'application/json' ,
0 commit comments