From 327b384938b1fdf44e77c5bd79e91b7fab0aaad4 Mon Sep 17 00:00:00 2001 From: Alejandro Garcia Anglada Date: Tue, 20 Oct 2020 11:14:00 +0100 Subject: [PATCH] ctx.errors: handles undefined and null values --- src/context/errors.test.ts | 7 +++++++ src/context/errors.ts | 14 ++++++++++---- 2 files changed, 17 insertions(+), 4 deletions(-) diff --git a/src/context/errors.test.ts b/src/context/errors.test.ts index 7bd2e0239..86be862a0 100644 --- a/src/context/errors.test.ts +++ b/src/context/errors.test.ts @@ -60,3 +60,10 @@ test('combines with data in the response JSON body', () => { }), ) }) + +test('bypasses undefined errors', () => { + const result = response(errors(undefined), errors(null)) + + expect(result.headers.get('content-type')).not.toEqual('application/json') + expect(result).toHaveProperty('body', null) +}) diff --git a/src/context/errors.ts b/src/context/errors.ts index 0c1dd708a..f82686658 100644 --- a/src/context/errors.ts +++ b/src/context/errors.ts @@ -3,10 +3,16 @@ import { ResponseTransformer } from '../response' import { json } from './json' /** - * Returns a list of GraphQL errors. + * Sets a given list of GraphQL errors on the mocked response. */ -export const errors = ( - errorsList: Partial[], -): ResponseTransformer<{ errors: typeof errorsList }> => { +export const errors = < + ErrorsType extends Partial[] | null | undefined +>( + errorsList: ErrorsType, +): ResponseTransformer<{ errors: ErrorsType }> => { + if (errorsList == null) { + return (res) => res + } + return json({ errors: errorsList }, { merge: true }) }