import * as chaiAsPromised from 'chai-as-promised' ; import { expect , use } from 'chai' ; import 'mocha' ; use ( chaiAsPromised ) ; import { Fetch , fetchWithRetry } from '../src/fetch' ; describe ( '#fetchWithRetry' , ( ) => { const fakeFetchFactory = ( numberOfFailures ) : Fetch => { return async ( _ ) => { if ( numberOfFailures > 0 ) { numberOfFailures -= 1 ; throw new Error ( `Failed: ${ numberOfFailures + 1 }` ) ; } return { arrayBuffer : ( ) => Promise . resolve ( new ArrayBuffer ( 0 ) ) , json : ( ) => Promise . resolve ( { } ) , text : ( ) => Promise . resolve ( `${ numberOfFailures }` ) , } ; } ; } ; it ( 'succeeds on first try' , async ( ) => { const response = await fetchWithRetry ( fakeFetchFactory ( 0 ) , 'https://example.com' ) ; expect ( await response . text ( ) ) . to . equal ( '0' ) ; } ) ; it ( 'succeeds on second try' , async ( ) => { const response = await fetchWithRetry ( fakeFetchFactory ( 1 ) , 'https://example.com' ) ; expect ( await response . text ( ) ) . to . equal ( '0' ) ; } ) ; it ( 'succeeds on third try' , async ( ) => { const response = await fetchWithRetry ( fakeFetchFactory ( 2 ) , 'https://example.com' ) ; expect ( await response . text ( ) ) . to . equal ( '0' ) ; } ) ; it ( 'succeeds on fourth try' , async ( ) => { const response = await fetchWithRetry ( fakeFetchFactory ( 3 ) , 'https://example.com' ) ; expect ( await response . text ( ) ) . to . equal ( '0' ) ; } ) ; it ( 'fails on fifth try' , async ( ) => { await expect ( fetchWithRetry ( fakeFetchFactory ( 4 ) , 'https://example.com' ) ) . to . be . rejectedWith ( Error , 'Failed: 1' ) ; } ) ; } ) ;