http-redirects.ts
This file
Path
test/http-redirects.ts
154 lines · 5.9 KiB · TypeScript
Last changed by
More testsSindre Sorhusbefore adoptioncd1dba0
History of this fileTake it
More testsSindre Sorhusbefore adoptioncd1dba0
lines 1–154why, one step back1import test from 'ava';2import ky, {HTTPError, NetworkError} from '../source/index.js';3import {createHttpTestServer} from './helpers/create-http-test-server.js';4import {parseRawBody} from './helpers/parse-body.js';56// Fetch §4.5 steps 12 and 14 specify method rewriting and body replay; RFC 9110 §§15.4.2–15.4.4, 15.4.8–15.4.9 define these statuses.7// https://fetch.spec.whatwg.org/#http-redirect-fetch8for (const [status, method, redirectedMethod] of [9 [301, 'POST', 'GET'],10 [302, 'POST', 'GET'],11 [303, 'POST', 'GET'],12 [303, 'PUT', 'GET'],13 [301, 'PUT', 'PUT'],14 [302, 'PATCH', 'PATCH'],15 [307, 'POST', 'POST'],16 [308, 'PUT', 'PUT'],17] as const) {18 test(`${status} redirects ${method} as ${redirectedMethod} with the expected body and headers`, async t => {19 const server = await createHttpTestServer(t, {bodyParser: false});20 const body = 'redirect payload';21 const requests: Array<{method: string; body: string}> = [];22 const bodyHeaders = {23 'content-type': 'text/plain',24 'content-encoding': 'identity',25 'content-language': 'en',26 'content-location': '/representation',27 };28 server.all('/start', async (request, response) => {29 requests.push({method: request.method, body: await parseRawBody(request)});30 response.writeHead(status, {location: '/destination'}).end();31 });32 server.all('/destination', async (request, response) => {33 requests.push({method: request.method, body: await parseRawBody(request)});34 response.json(request.headers);35 });3637 const response = await ky(`${server.url}/start`, {38 method,39 body,40 headers: {...bodyHeaders, 'x-preserved': 'yes'},41 retry: 0,42 });43 const headers = await response.json<Record<string, string>>();44 t.deepEqual(requests, [45 {method, body},46 {method: redirectedMethod, body: redirectedMethod === 'GET' ? '' : body},47 ]);48 t.is(headers['x-preserved'], 'yes');49 for (const [name, value] of Object.entries(bodyHeaders)) {50 t.is(headers[name], redirectedMethod === 'GET' ? undefined : value);51 }5253 // RFC 9110 §15.4 requires removing content-specific headers when switching to GET.54 t.is(headers['content-length'], redirectedMethod === 'GET' ? undefined : String(body.length));55 t.is(response.url, `${server.url}/destination`);56 t.true(response.redirected);57 });58}5960// Fetch §4.5 step 12 excludes both GET and HEAD from the 303 rewrite.61for (const method of ['GET', 'HEAD'] as const) {62 test(`303 preserves ${method}`, async t => {63 const server = await createHttpTestServer(t);64 const methods: string[] = [];65 server.all('/start', (request, response) => {66 methods.push(request.method);67 response.writeHead(303, {location: '/destination'}).end();68 });69 server.all('/destination', (request, response) => {70 methods.push(request.method);71 response.set('x-method', request.method).end('destination');72 });7374 const response = await ky(`${server.url}/start`, {method, retry: 0});75 t.deepEqual(methods, [method, method]);76 t.is(response.headers.get('x-method'), method);77 t.is(await response.text(), method === 'HEAD' ? '' : 'destination');78 });79}8081// Fetch §4.4 step 6.3 controls redirect modes. Node exposes the actual manual response instead of a browser's opaque-redirect response.82// https://github.com/nodejs/undici#manual-redirect83for (const throwHttpErrors of [undefined, false]) {84 test(`manual redirects are not followed with throwHttpErrors ${throwHttpErrors ?? 'default'}`, async t => {85 const server = await createHttpTestServer(t);86 const paths: string[] = [];87 server.use((request, response) => {88 paths.push(request.path);89 response.writeHead(302, {location: '/destination', 'content-type': 'text/plain'}).end('Moved');90 });9192 const result = ky(`${server.url}/start`, {redirect: 'manual', throwHttpErrors, retry: 0});93 if (throwHttpErrors === undefined) {94 const error = await t.throwsAsync(result, {instanceOf: HTTPError});95 t.is(error.response.status, 302);96 t.is(error.response.headers.get('location'), '/destination');97 t.is(error.data, 'Moved');98 } else {99 const response = await result;100 t.is(response.status, 302);101 t.is(response.headers.get('location'), '/destination');102 t.false(response.redirected);103 t.is(await response.text(), 'Moved');104 }105106 t.deepEqual(paths, ['/start']);107 });108}109110test('redirect error mode produces a NetworkError without following or retrying', async t => {111 const server = await createHttpTestServer(t);112 const paths: string[] = [];113 server.use((request, response) => {114 paths.push(request.path);115 response.writeHead(302, {location: '/destination'}).end();116 });117118 await t.throwsAsync(ky(`${server.url}/start`, {redirect: 'error', retry: 0}), {instanceOf: NetworkError});119 t.deepEqual(paths, ['/start']);120});121122test('relative Location resolves against the redirecting request URL', async t => {123 // RFC 9110 §10.2.2: https://www.rfc-editor.org/rfc/rfc9110.html#section-10.2.2124 const server = await createHttpTestServer(t);125 const paths: string[] = [];126 server.get('/directory/start', (request, response) => {127 paths.push(request.url);128 response.writeHead(302, {location: '../destination?from=redirect'}).end();129 });130 server.get('/destination', (request, response) => {131 paths.push(request.url);132 response.end('arrived');133 });134135 const response = await ky(`${server.url}/directory/start?original=yes`, {retry: 0});136 t.is(await response.text(), 'arrived');137 t.deepEqual(paths, ['/directory/start?original=yes', '/destination?from=redirect']);138 t.is(response.url, `${server.url}/destination?from=redirect`);139});140141test('a redirect status without Location remains an HTTPError', async t => {142 // Fetch §4.5 step 4 returns the response when there is no location URL.143 const server = await createHttpTestServer(t);144 let requests = 0;145 server.get('/', (_request, response) => {146 requests++;147 response.status(302).type('text').end('No destination');148 });149150 const error = await t.throwsAsync(ky(server.url, {retry: 0}), {instanceOf: HTTPError});151 t.is(error.response.status, 302);152 t.is(error.data, 'No destination');153 t.is(requests, 1);154});