From 4c41c38d03a3a29b3474a9544df5d4df71029787 Mon Sep 17 00:00:00 2001 From: Zach Shilton <4624598+zchsh@users.noreply.github.com> Date: Fri, 5 Mar 2021 21:31:42 -0500 Subject: [PATCH] Support nested-only testValue defs, with explicit undefined opt-out --- testing.js | 17 ++++++++++++----- testing.test.js | 5 +++-- 2 files changed, 15 insertions(+), 7 deletions(-) diff --git a/testing.js b/testing.js index 5370367..aec5415 100644 --- a/testing.js +++ b/testing.js @@ -31,13 +31,20 @@ function getTestValues(propsSpec) { } } } else if (typeof prop.properties === 'object') { - // if properties is an object, and the `testValue` is also an object, - // we can recurse and assign the results directly - if (typeof memo[name] === 'object') { + // if properties is an object, we can recurse and build a testValue for the object + const hasBaseValue = typeof memo[name] === 'object' + const hasValueSet = prop.hasOwnProperty('testValue') + // in most cases, we'll recurse and build the testValue + if (hasBaseValue || !hasValueSet) { + // if the base value was not set, we need to initialize it + if (typeof memo[name] === 'undefined') memo[name] = {} + // we override the base testValue with nested testValues Object.assign(memo[name], getTestValues(prop.properties)) - } else if (typeof memo[name] === 'undefined') { - // do nothing, there is no test value and thats ok + } else if (hasValueSet && typeof prop.testValue === 'undefined') { + // in some cases, prop authors explicitly set testValue: undefined. + // in these cases, we should not recurse and construct a testValue } else { + // in all other cases we should throw an error throw new Error( `The property "${name}" has a "properties" key, which requires an array or object type, but its "testValue" is ${JSON.stringify( memo[name] diff --git a/testing.test.js b/testing.test.js index 183d411..f3853b0 100644 --- a/testing.test.js +++ b/testing.test.js @@ -49,7 +49,7 @@ test('nested values with an array containing a monotype', () => { expect(res.base[0]).toBe('nested-string') }) -test('no test values used at all', () => { +test('no test values used at all, when explicitly passing undefined', () => { const res = getTestValues({ base: { properties: { @@ -67,6 +67,7 @@ test('no test values used at all', () => { }, }, }, + testValue: undefined, }, }) expect(res).toEqual({}) @@ -140,5 +141,5 @@ test('sub-properties define test values but base property is undefined', () => { }, }, }) - expect(res).toEqual({}) + expect(res).toEqual({ base: { foo: 'nested' } }) })