From de5132c4fd0c3be43c8459d2b2ff23e444b368d2 Mon Sep 17 00:00:00 2001 From: Patrick McLaughlin Date: Fri, 3 Jun 2022 10:43:04 -0400 Subject: [PATCH] fix(superagent): do not throw on non-2xx status Ticket: BG-47455 --- packages/superagent-wrapper/src/request.ts | 4 +++ .../superagent-wrapper/test/request.test.ts | 32 ++++++++++++++++++- 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/packages/superagent-wrapper/src/request.ts b/packages/superagent-wrapper/src/request.ts index 515e62f8..5901b0e4 100644 --- a/packages/superagent-wrapper/src/request.ts +++ b/packages/superagent-wrapper/src/request.ts @@ -139,6 +139,10 @@ const patchRequest = ( return res as ExpectedDecodedResponse; } }); + + // Stop superagent from throwing on non-2xx status codes + patchedReq.ok(() => true); + return patchedReq; }; diff --git a/packages/superagent-wrapper/test/request.test.ts b/packages/superagent-wrapper/test/request.test.ts index 52d9cea0..8c4fe213 100644 --- a/packages/superagent-wrapper/test/request.test.ts +++ b/packages/superagent-wrapper/test/request.test.ts @@ -5,9 +5,11 @@ import express from 'express'; import * as E from 'fp-ts/Either'; import * as t from 'io-ts'; import { NumberFromString } from 'io-ts-types'; +import superagent from 'superagent'; import supertest from 'supertest'; +import { URL } from 'url'; -import { supertestRequestFactory } from '../src/request'; +import { superagentRequestFactory, supertestRequestFactory } from '../src/request'; import { buildApiClient } from '../src/routes'; const PostTestRoute = h.httpRoute({ @@ -184,4 +186,32 @@ describe('request', () => { assert.isTrue(result); }); }); + + describe('superagent', async () => { + it('does not throw on non-2xx status codes', async () => { + // Figure out what host/port supertest set up (the response is just thrown away on purpose) + const superTestReq = apiClient['api.v1.test'].post({ + id: 1337, + foo: 'test', + bar: 42, + }); + + // Construct an api client that uses superagent, with the base url extracted from the supertest + // request above. + const url = new URL(superTestReq.url); + url.pathname = '/'; + const superagentClient = buildApiClient( + superagentRequestFactory(superagent, url.toString()), + TestRoutes, + ); + + const req = await superagentClient['api.v1.test'] + .post({ id: 1337, foo: 'test', bar: 42 }) + .set('x-send-unexpected-status-code', 'true') + .decode(); + + assert.equal(req.status, 'decodeError'); + assert.equal(req.original.status, 400); + }); + }); });