From 358ceaf797ecfc38f83b49c2b9b695fafdb6aeee Mon Sep 17 00:00:00 2001 From: John Ruble Date: Wed, 15 Mar 2023 16:44:07 -0400 Subject: [PATCH] test that resolveResponse does not mutate input (currently failing) --- test/unit/deep-freeze.js | 16 ++++++++++++++++ test/unit/index-test.js | 25 +++++++++++++++++-------- 2 files changed, 33 insertions(+), 8 deletions(-) create mode 100644 test/unit/deep-freeze.js diff --git a/test/unit/deep-freeze.js b/test/unit/deep-freeze.js new file mode 100644 index 0000000..b1b844f --- /dev/null +++ b/test/unit/deep-freeze.js @@ -0,0 +1,16 @@ +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze#examples +export function deepFreeze(object) { + // Retrieve the property names defined on object + const propNames = Reflect.ownKeys(object) + + // Freeze properties before freezing self + for (const name of propNames) { + const value = object[name] + + if ((value && typeof value === 'object') || typeof value === 'function') { + deepFreeze(value) + } + } + + return Object.freeze(object) +} diff --git a/test/unit/index-test.js b/test/unit/index-test.js index 5f5aa86..a288f97 100644 --- a/test/unit/index-test.js +++ b/test/unit/index-test.js @@ -1,5 +1,7 @@ -const { deepEqual, notEqual, equal, notDeepEqual } = require('chai').assert +const { deepEqual, notEqual, equal, notDeepEqual, doesNotThrow } = require('chai').assert const resolveResponse = require('../../index') +const { deepFreeze } = require('./deep-freeze') +const copy = require('fast-copy') describe('Resolve a', function () { it('empty response which returns an empty response', function () { @@ -493,8 +495,8 @@ describe('Resolve a', function () { equal(resolved[0].fields.linkfield[2].fields.linkfield[0].sys.id, 'Y', 'sub link id') }) - it('response with links should resolve complex references between items and includes', function () { - const items = [ + const example = { + items: [ { sys: { type: 'Entry', @@ -552,8 +554,8 @@ describe('Resolve a', function () { }, }, }, - ] - const includes = { + ], + includes: { Animal: [ { sys: { @@ -619,9 +621,11 @@ describe('Resolve a', function () { fields: { name: 'Aussie Parrot' }, }, ], - } - - const resolved = resolveResponse({ items, includes }) + }, + } + it('response with links should resolve complex references between items and includes', function () { + const resolved = resolveResponse(example) + const { includes } = example deepEqual(resolved[0].fields.animal.sys, includes.Animal[0].sys, 'pig') deepEqual(resolved[0].fields.animal.fields.friend.sys, includes.Animal[1].sys, 'groundhog') deepEqual(resolved[0].fields.anotheranimal.sys.type, 'Link', 'first middle parrot not resolved') @@ -1044,4 +1048,9 @@ describe('Resolve a', function () { const resolved = resolveResponse({ items, includes }) deepEqual(resolved, items) }) + + it('does not mutate input', function () { + const frozenCopy = deepFreeze(copy(example)) + doesNotThrow(() => resolveResponse(frozenCopy)) + }) })