Skip to content
Myr

http-metadata.ts

This file

Path

test/http-metadata.ts

198 lines · 8.1 KiB · TypeScript

Last changed by

More testsSindre Sorhusbefore adoptioncd1dba0

History of this file

Take it

More testsSindre Sorhusbefore adoptioncd1dba0

lines 1–198why, one step back
1import test from 'ava';
2import ky, {HTTPError} from '../source/index.js';3import {createHttpTestServer} from './helpers/create-http-test-server.js';45// Node exposes Set-Cookie response headers. Browsers filter them out before Ky receives the response.6// Unlike list-valued fields, Set-Cookie must remain separate, including commas inside Expires (RFC 9110 §5.3).7// https://www.rfc-editor.org/rfc/rfc9110.html#section-5.38for (const mode of ['plain', 'progress', 'hook replacement', 'custom parser'] as const) {9 test(`response cookies remain separate through ${mode} and cloning`, async t => {10 const server = await createHttpTestServer(t);11 const cookies = ['session=one; Path=/; HttpOnly', 'theme=dark; Expires=Wed, 01 Jan 2031 00:00:00 GMT; Path=/'];12 server.get('/', (_request, response) => {13 response.writeHead(200, {'set-cookie': cookies, vary: ['Accept', 'Accept-Language'], 'content-type': 'application/json'}).end('{"ok":true}');14 });15 let hookCalls = 0;16 let parserCalls = 0;17 let progressCalls = 0;18 const response = await ky(server.url, {19 onDownloadProgress: mode === 'progress'20 ? () => {21 progressCalls++;22 }23 : undefined,24 hooks: {25 afterResponse: mode === 'hook replacement'26 ? [({response}) => {27 hookCalls++;28 t.deepEqual(response.headers.getSetCookie(), cookies);29 return new Response(response.body, response);30 }]31 : [],32 },33 parseJson: mode === 'custom parser'34 ? (text, {response}) => {35 parserCalls++;36 t.deepEqual(response.headers.getSetCookie(), cookies);37 return JSON.parse(text);38 }39 : undefined,40 });41 const clone = response.clone();42 for (const result of [response, clone]) {43 t.deepEqual(result.headers.getSetCookie(), cookies);44 t.is(result.headers.get('vary'), 'Accept, Accept-Language');45 // eslint-disable-next-line no-await-in-loop46 t.deepEqual(await result.json(), {ok: true});47 }4849 t.is(hookCalls, mode === 'hook replacement' ? 1 : 0);50 t.is(parserCalls, mode === 'custom parser' ? 2 : 0);51 t.is(progressCalls > 0, mode === 'progress');52 });53}5455test('HTTPError retains separate response cookies after parsing error data', async t => {56 const server = await createHttpTestServer(t);57 const cookies = ['session=; Max-Age=0; Path=/', 'notice=expired; Path=/'];58 server.get('/', (_request, response) => {59 response.writeHead(401, {'set-cookie': cookies, 'www-authenticate': 'Bearer realm="example"', 'content-type': 'application/json'}).end('{"error":"expired"}');60 });61 const error = await t.throwsAsync(ky(server.url), {instanceOf: HTTPError});6263 t.deepEqual(error.data, {error: 'expired'});64 t.deepEqual(error.response.headers.getSetCookie(), cookies);65 t.is(error.response.headers.get('www-authenticate'), 'Bearer realm="example"');66});6768// These fixtures test preservation of preconditions and Ky's error policy, not server-side condition evaluation.69// RFC 9110 §§13.1.1, 13.1.2, and 13.1.4 require 412 when these write preconditions fail.70for (const [name, value] of [71 ['if-match', '"old-version", "other-version"'],72 ['if-none-match', '*'],73 ['if-unmodified-since', 'Wed, 01 Jan 2025 00:00:00 GMT'],74] as const) {75 test(`failed ${name} write preconditions retain metadata and do not retry`, async t => {76 const server = await createHttpTestServer(t);77 let requests = 0;78 server.put('/', (request, response) => {79 requests++;80 t.is(request.headers[name], value);81 t.deepEqual(request.body, {updated: true});82 response.writeHead(412, {etag: '"current-version"', 'content-type': 'application/json'}).end('{"error":"precondition failed"}');83 });84 const error = await t.throwsAsync(ky.put(server.url, {headers: {[name]: value}, json: {updated: true}}), {instanceOf: HTTPError});8586 t.is(error.response.status, 412);87 t.is(error.response.headers.get('etag'), '"current-version"');88 t.deepEqual(error.data, {error: 'precondition failed'});89 t.is(requests, 1);90 });91}9293test('an If-Range mismatch may return the complete representation as 200', async t => {94 // RFC 9110 §13.1.5: a failed If-Range condition means the server ignores Range.95 const server = await createHttpTestServer(t);96 server.get('/', (request, response) => {97 t.is(request.headers.range, 'bytes=5-');98 t.is(request.headers['if-range'], '"old-version"');99 response.writeHead(200, {etag: '"new-version"', 'content-length': '10'}).end('0123456789');100 });101 const response = await ky(server.url, {headers: {range: 'bytes=5-', 'if-range': '"old-version"'}});102103 t.is(response.status, 200);104 t.is(response.headers.get('etag'), '"new-version"');105 t.false(response.headers.has('content-range'));106 t.is(await response.text(), '0123456789');107});108109test('201 Location identifies the created resource without following it', async t => {110 // RFC 9110 §15.3.2: Location on a 201 is not an HTTP redirect.111 const server = await createHttpTestServer(t);112 const requests: string[] = [];113 server.use((request, response) => {114 requests.push(`${request.method} ${request.path}`);115 response.writeHead(201, {location: '/created/123', 'content-type': 'application/json'}).end('{"id":123}');116 });117 const response = await ky.post(server.url, {json: {name: 'example'}});118119 t.is(response.status, 201);120 t.is(response.headers.get('location'), '/created/123');121 t.false(response.redirected);122 t.deepEqual(await response.json(), {id: 123});123 t.deepEqual(requests, ['POST /']);124});125126test('202 with Retry-After returns the pending representation without polling', async t => {127 // RFC 9110 §15.3.3 describes acceptance, not completion. Ky does not automatically poll accepted jobs.128 const server = await createHttpTestServer(t);129 let requests = 0;130 server.get('/', (_request, response) => {131 requests++;132 response.writeHead(202, {'retry-after': '0', location: '/jobs/123', 'content-type': 'application/json'}).end('{"pending":true}');133 });134 const response = await ky(server.url);135136 t.is(response.status, 202);137 t.is(response.headers.get('retry-after'), '0');138 t.deepEqual(await response.json(), {pending: true});139 t.is(requests, 1);140});141142test('300 with Location remains an HTTPError instead of following a redirect', async t => {143 // Fetch only follows 301, 302, 303, 307, and 308: https://fetch.spec.whatwg.org/#redirect-status144 const server = await createHttpTestServer(t);145 const paths: string[] = [];146 server.use((request, response) => {147 paths.push(request.path);148 response.writeHead(300, {location: '/preferred', 'content-type': 'text/plain'}).end('Choose a representation');149 });150 const error = await t.throwsAsync(ky(server.url), {instanceOf: HTTPError});151152 t.is(error.response.status, 300);153 t.is(error.response.headers.get('location'), '/preferred');154 t.is(error.data, 'Choose a representation');155 t.deepEqual(paths, ['/']);156});157158test('informational responses do not replace the final response or leak their headers', async t => {159 // RFC 9110 §15.2: an informational response precedes the final response.160 const server = await createHttpTestServer(t);161 server.get('/', (_request, response) => {162 response.writeEarlyHints({link: '</style.css>; rel=preload; as=style', 'x-early-only': 'hint'});163 response.writeHead(200, {'content-type': 'application/json', 'x-final': 'yes'}).end('{"final":true}');164 });165 const statuses: number[] = [];166 const response = await ky(server.url, {167 hooks: {168 afterResponse: [({response}) => {169 statuses.push(response.status);170 }],171 },172 });173174 t.is(response.status, 200);175 t.is(response.headers.get('x-final'), 'yes');176 t.false(response.headers.has('x-early-only'));177 t.false(response.headers.has('link'));178 t.deepEqual(await response.json(), {final: true});179 t.deepEqual(statuses, [200]);180});181182test('duplicate Accept entries retain preference order and quality values', async t => {183 // RFC 9110 §§5.3 and 12.5.1: list order and quality parameters must survive header combination.184 const server = await createHttpTestServer(t);185 server.get('/', (request, response) => {186 t.is(request.headers.accept, 'application/problem+json, application/json;q=0.9, */*;q=0.1');187 response.json({negotiated: true});188 });189 const result = await ky(server.url, {190 headers: [191 ['Accept', 'application/problem+json'],192 ['accept', 'application/json;q=0.9'],193 ['ACCEPT', '*/*;q=0.1'],194 ],195 }).json();196197 t.deepEqual(result, {negotiated: true});198});