diff --git a/src/serializers/JSONSerializer/index.test.ts b/src/serializers/JSONSerializer/index.test.ts index e38c10a..afd9c1b 100644 --- a/src/serializers/JSONSerializer/index.test.ts +++ b/src/serializers/JSONSerializer/index.test.ts @@ -9,11 +9,20 @@ describe(`when serializing errors`, () => { describe(`when serializing buffers`, () => { test('should stringify the buffer', () => { - const got = JSONSerializer({ word: Buffer.from('example') }) + const got = JSONSerializer({ word: Buffer.from('example') }) expect(got).toEqual(`{"word":"example"}`) }) }) +describe(`when serializing undefined or null objects`, () => { + test.each([ + [undefined, undefined], + [null, 'null'], + ])('should not attempt to serialize', (input, expected) => { + expect(JSONSerializer(input)).toEqual(expected) + }) +}) + // more info // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Cyclic_object_value describe(`when serializing recursive objects`, () => { diff --git a/src/serializers/JSONSerializer/index.ts b/src/serializers/JSONSerializer/index.ts index 2b5d4be..9d60ad3 100644 --- a/src/serializers/JSONSerializer/index.ts +++ b/src/serializers/JSONSerializer/index.ts @@ -19,14 +19,14 @@ function getCircularReplacer() { // toStringers strigifies some specific types function toStringers(_: any, value: any) { + // exit early for null and undefined + if (value === undefined || value === null) return value // error - if (value instanceof Error) - return value.toString() + if (value instanceof Error) return value.toString() // buffer - if (value.type !== undefined && value.type === "Buffer") - return Buffer.from(value).toString() + if (value.type === 'Buffer') return Buffer.from(value).toString() return value }