Skip to content

Commit

Permalink
Don't break on null and undefined by only considering objects for ser…
Browse files Browse the repository at this point in the history
…ialization
  • Loading branch information
flommy committed Dec 4, 2020
1 parent ce27216 commit d326e7a
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 5 deletions.
19 changes: 19 additions & 0 deletions __snapshots__/test.js.snap
Original file line number Diff line number Diff line change
@@ -1,11 +1,30 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`should not serialize array 1`] = `
Array [
true,
"a",
1,
Object {
"foo": "bar",
},
null,
undefined,
]
`;

exports[`should not serialize non-HTTP response 1`] = `
Object {
"foo": "bar",
"null": null,
"undefined": undefined,
}
`;

exports[`should not serialize null 1`] = `null`;

exports[`should not serialize undefined 1`] = `undefined`;

exports[`should serialize HTTP Buffer response 1`] = `
{
"$schema": "http://json-schema.org/draft-04/schema#",
Expand Down
10 changes: 6 additions & 4 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,16 @@
const sortKeys = require('sort-keys')
const toSchema = require('generate-schema').json

const isObject = res => typeof res === 'object' && !!res
const isSupertest = res => res.status && res.body
const isLightMyRequest = res => res.statusCode && res.body

const JSONRestAPISnapshotSerializer = {
test: (res) => [
isSupertest,
isLightMyRequest
].some(testFn => testFn(res)),
test: (res) =>
isObject(res) && [
isSupertest,
isLightMyRequest
].some(testFn => testFn(res)),
print: ({ body }) => {
const contents = tryParse(body)
const schema = sortKeys(toSchema(contents), { deep: true })
Expand Down
14 changes: 13 additions & 1 deletion test.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ const serializer = require('./')
expect.addSnapshotSerializer(serializer)

test('should not serialize non-HTTP response', () => {
const object = { foo: 'bar' }
const object = { foo: 'bar', null: null, undefined: undefined }
expect(object).toMatchSnapshot()
})

Expand All @@ -23,3 +23,15 @@ test('should serialize LightMyRequest HTTP response', () => {
const object = { statusCode: 200, body: '{ "Hello": "World" }' }
expect(object).toMatchSnapshot()
})

test('should not serialize null', () => {
expect(null).toMatchSnapshot()
})

test('should not serialize undefined', () => {
expect(undefined).toMatchSnapshot()
})

test('should not serialize array', () => {
expect([true, 'a', 1, { foo: 'bar' }, null, undefined]).toMatchSnapshot()
})

0 comments on commit d326e7a

Please sign in to comment.