Skip to content
Myr

retry-options.ts

This file

Path

test/retry-options.ts

318 lines · 9.0 KiB · TypeScript

Last changed by

Let a `beforeRetry` hook change per-attempt optionsSindre Sorhusbefore adoption242c327

History of this file

Take it

Let a `beforeRetry` hook change per-attempt optionsSindre Sorhusbefore adoption242c327

lines 1–318why, one step back
1import test from 'ava';
2import ky from '../source/index.js';3import {createHttpTestServer} from './helpers/create-http-test-server.js';45// Retries right away, so the tests do not wait for a backoff.6const retryOnce = {limit: 1, delay: () => 0};78// A `fetch` that always answers `503` and counts its calls.9const createUnavailableFetch = () => {10 const state = {11 calls: 0,12 async fetch() {13 state.calls++;14 return new Response('retry', {status: 503});15 },16 };1718 return state;19};2021test('beforeRetry can turn off upload progress without losing the body', async t => {22 let attempts = 0;23 const progressAttempts: number[] = [];24 const response = await ky.put('https://example.com', {25 body: 'payload',26 retry: retryOnce,27 onUploadProgress() {28 progressAttempts.push(attempts);29 },30 async fetch(request) {31 attempts++;32 t.is(await request.text(), 'payload');33 if (attempts === 1) {34 throw new TypeError('Failed to fetch');35 }3637 return new Response('ok');38 },39 hooks: {40 beforeRetry: [() => ({options: {onUploadProgress: undefined}})],41 },42 });4344 t.is(await response.text(), 'ok');45 t.is(attempts, 2);46 t.deepEqual(progressAttempts, [1]);47});4849test('beforeRetry can turn on upload progress without losing the body', async t => {50 let attempts = 0;51 const progressAttempts: number[] = [];52 const response = await ky.put('https://example.com', {53 body: 'payload',54 retry: retryOnce,55 async fetch(request) {56 attempts++;57 t.is(await request.text(), 'payload');58 if (attempts === 1) {59 throw new TypeError('Failed to fetch');60 }6162 return new Response('ok');63 },64 hooks: {65 beforeRetry: [() => ({66 options: {67 onUploadProgress() {68 progressAttempts.push(attempts);69 },70 },71 })],72 },73 });7475 t.is(await response.text(), 'ok');76 t.deepEqual(progressAttempts, [2]);77});7879test('beforeRetry options apply to later retries and later hooks', async t => {80 let attempts = 0;81 let originalProgressCalls = 0;82 let replacementProgressCalls = 0;83 const originalProgress = () => {84 originalProgressCalls++;85 };8687 const replacementProgress = () => {88 replacementProgressCalls++;89 };9091 const seenProgress: unknown[] = [];92 const text = await ky('https://example.com', {93 onDownloadProgress: originalProgress,94 retry: {...retryOnce, limit: 2},95 async fetch() {96 attempts++;97 return new Response('ok', {status: attempts < 3 ? 503 : 200});98 },99 hooks: {100 beforeRetry: [101 ({options, retryCount}) => {102 seenProgress.push(options.onDownloadProgress);103 if (retryCount === 1) {104 return {options: {onDownloadProgress: replacementProgress}};105 }106 },107 ({options}) => {108 t.is(options.onDownloadProgress, replacementProgress);109 },110 ],111 },112 }).text();113114 t.is(text, 'ok');115 t.is(attempts, 3);116 t.deepEqual(seenProgress, [originalProgress, replacementProgress]);117 t.is(originalProgressCalls, 0);118 t.true(replacementProgressCalls > 0);119});120121test('beforeRetry can change fetch and throwHttpErrors', async t => {122 const unavailable = createUnavailableFetch();123 let replacementFetchCalls = 0;124 const response = await ky('https://example.com', {125 retry: retryOnce,126 fetch: unavailable.fetch,127 hooks: {128 beforeRetry: [() => ({129 options: {130 async fetch() {131 replacementFetchCalls++;132 return new Response('still failing', {status: 500});133 },134 throwHttpErrors: false,135 },136 })],137 },138 });139140 t.is(response.status, 500);141 t.is(unavailable.calls, 1);142 t.is(replacementFetchCalls, 1);143});144145test('beforeRetry can change throwHttpErrors to a function', async t => {146 const unavailable = createUnavailableFetch();147 const statuses: number[] = [];148 const response = await ky('https://example.com', {149 retry: retryOnce,150 fetch: unavailable.fetch,151 hooks: {152 beforeRetry: [() => ({153 options: {154 throwHttpErrors(status) {155 statuses.push(status);156 return false;157 },158 },159 })],160 },161 });162163 t.is(response.status, 503);164 t.deepEqual(statuses, [503]);165});166167test('beforeRetry can change the timeout', async t => {168 let attempts = 0;169 const response = await ky('https://example.com', {170 timeout: 10,171 retry: {...retryOnce, retryOnTimeout: true},172 async fetch(request) {173 attempts++;174 await new Promise(resolve => {175 setTimeout(resolve, 50);176 });177 request.signal.throwIfAborted();178 return new Response('ok');179 },180 hooks: {181 beforeRetry: [() => ({options: {timeout: 1000}})],182 },183 });184185 t.is(await response.text(), 'ok');186 t.is(attempts, 2);187});188189test('beforeRetry options apply to a response returned by a later hook', async t => {190 const unavailable = createUnavailableFetch();191 const response = await ky('https://example.com', {192 retry: retryOnce,193 fetch: unavailable.fetch,194 hooks: {195 beforeRetry: [196 () => ({options: {throwHttpErrors: false}}),197 () => new Response('from hook', {status: 500}),198 ],199 },200 });201202 t.is(response.status, 500);203 t.is(await response.text(), 'from hook');204 t.is(unavailable.calls, 1);205});206207test('beforeRetry `undefined` restores the global fetch', async t => {208 const server = await createHttpTestServer(t);209 server.get('/', (_request, response) => {210 response.end('native');211 });212213 const unavailable = createUnavailableFetch();214 const result = await ky(server.url, {215 retry: retryOnce,216 fetch: unavailable.fetch,217 hooks: {beforeRetry: [() => ({options: {fetch: undefined}})]},218 }).text();219220 t.is(result, 'native');221 t.is(unavailable.calls, 1);222});223224test('beforeRetry `undefined` restores Ky\'s default rather than the instance value', async t => {225 let attempts = 0;226 const api = ky.create({227 throwHttpErrors: false,228 retry: retryOnce,229 async fetch() {230 attempts++;231 if (attempts === 1) {232 throw new TypeError('Failed to fetch');233 }234235 return new Response('failed', {status: 500});236 },237 });238239 await t.throwsAsync(api('https://example.com', {240 hooks: {beforeRetry: [() => ({options: {throwHttpErrors: undefined}})]},241 }), {name: 'HTTPError'});242 t.is(attempts, 2);243});244245test('beforeRetry options do not leak into other requests from the same instance', async t => {246 let progressCalls = 0;247 const attempts = new Map<string, number>();248 const api = ky.create({249 retry: retryOnce,250 onUploadProgress() {251 progressCalls++;252 },253 async fetch(request) {254 const count = (attempts.get(request.url) ?? 0) + 1;255 attempts.set(request.url, count);256 await request.text();257 return new Response('ok', {status: count === 1 ? 503 : 200});258 },259 });260261 await api.put('https://example.com/changed', {262 body: 'payload',263 hooks: {beforeRetry: [() => ({options: {onUploadProgress: undefined}})]},264 });265 // A small body reports progress once per streamed attempt.266 t.is(progressCalls, 1);267268 await api.put('https://example.com/unchanged', {body: 'payload'});269 t.is(progressCalls, 3);270});271272test('beforeRetry options do not reset the retry limit', async t => {273 const unavailable = createUnavailableFetch();274 await t.throwsAsync(ky('https://example.com', {275 retry: {...retryOnce, limit: 2},276 fetch: unavailable.fetch,277 hooks: {beforeRetry: [() => ({options: {timeout: false}})]},278 }), {name: 'HTTPError'});279280 t.is(unavailable.calls, 3);281});282283const notAnOptionsObject = 'The `options` returned from a `beforeRetry` hook must be an object';284285for (const {name, update, message, errorClass = TypeError} of [286 {name: 'a missing `options`', update: {}, message: notAnOptionsObject},287 {name: 'array options', update: {options: []}, message: notAnOptionsObject},288 {name: '`null` options', update: {options: null}, message: notAnOptionsObject},289 {name: 'the `body` option', update: {options: {body: 'payload'}}, message: 'The `body` option cannot be changed from a `beforeRetry` hook'},290 {name: 'the `retry` option', update: {options: {retry: 10}}, message: 'The `retry` option cannot be changed from a `beforeRetry` hook'},291 {292 name: 'a `__proto__` key',293 update: {options: JSON.parse('{"__proto__": {"timeout": 1}}') as unknown},294 message: 'The `__proto__` option cannot be changed from a `beforeRetry` hook',295 },296 {name: 'an invalid callback', update: {options: {onUploadProgress: 'invalid'}}, message: 'The `onUploadProgress` option must be a function'},297 {name: 'a `null` fetch', update: {options: {fetch: null}}, message: 'The `fetch` option must be a function'},298 {name: 'an invalid throwHttpErrors', update: {options: {throwHttpErrors: 'yes'}}, message: 'The `throwHttpErrors` option must be a boolean or a function'},299 {name: 'a `null` throwHttpErrors', update: {options: {throwHttpErrors: null}}, message: 'The `throwHttpErrors` option must be a boolean or a function'},300 {name: 'a `null` timeout', update: {options: {timeout: null}}, message: 'The `timeout` option must be a non-negative number or `false`'},301 {302 name: 'an invalid timeout',303 update: {options: {timeout: 2 ** 31}},304 message: 'The `timeout` option cannot be greater than 2147483647',305 errorClass: RangeError,306 },307]) {308 test(`beforeRetry rejects ${name} before retrying`, async t => {309 const unavailable = createUnavailableFetch();310 await t.throwsAsync(ky('https://example.com', {311 retry: retryOnce,312 fetch: unavailable.fetch,313 hooks: {beforeRetry: [() => update as never]},314 }), {instanceOf: errorClass, message});315316 t.is(unavailable.calls, 1);317 });318}