From 464c2f10ac75b58bb6b270f34577048e8b23c6cf Mon Sep 17 00:00:00 2001 From: Zao Soula Date: Sat, 17 Feb 2024 01:45:25 +0100 Subject: [PATCH] feat(core/testers): add hasOption tester --- packages/core/src/testers/testers.ts | 19 +++++++++++++++++++ packages/core/test/testers.test.ts | 25 +++++++++++++++++++++++++ 2 files changed, 44 insertions(+) diff --git a/packages/core/src/testers/testers.ts b/packages/core/src/testers/testers.ts index c14048e335..98455cd087 100644 --- a/packages/core/src/testers/testers.ts +++ b/packages/core/src/testers/testers.ts @@ -31,6 +31,7 @@ import isArray from 'lodash/isArray'; import reduce from 'lodash/reduce'; import toPairs from 'lodash/toPairs'; import includes from 'lodash/includes'; +import isUndefined from 'lodash/isUndefined'; import type { Categorization, ControlElement, @@ -215,6 +216,24 @@ export const optionIs = return !isEmpty(options) && options[optionName] === optionValue; }; +/** + * Checks whether the given UI schema has an option with the given + * name. If no options property + * is set, returns false. + * + * @param {string} optionName the name of the option to check + */ +export const hasOption = + (optionName: string): Tester => + (uischema: UISchemaElement): boolean => { + if (isEmpty(uischema)) { + return false; + } + + const options = uischema.options; + return !isEmpty(options) && !isUndefined(options[optionName]); + }; + /** * Only applicable for Controls. * diff --git a/packages/core/test/testers.test.ts b/packages/core/test/testers.test.ts index fcbf8cf9e1..346fb9d006 100644 --- a/packages/core/test/testers.test.ts +++ b/packages/core/test/testers.test.ts @@ -54,6 +54,7 @@ import { JsonSchema, LabelElement, UISchemaElement, + hasOption, } from '../src'; const test = anyTest as TestInterface<{ uischema: ControlElement }>; @@ -183,6 +184,30 @@ test('optionIs should return false for UI schema elements without options cell', t.false(optionIs('answer', 42)(control, undefined, undefined)); }); +test('hasOption should check for options', (t) => { + const control: ControlElement = { + type: 'Control', + scope: '#/properties/bar', + options: { + answer: 42, + }, + }; + t.true(hasOption('answer')(control, undefined, undefined)); +}); + +test('hasOption should not fail if uischema is undefined or null', (t) => { + const uischema: UISchemaElement = null; + t.false(hasOption('answer')(uischema, undefined, undefined)); +}); + +test('hasOption should return false for UI schema elements without options cell', (t) => { + const control: ControlElement = { + type: 'Control', + scope: '#/properties/bar', + }; + t.false(hasOption('answer')(control, undefined, undefined)); +}); + test('schemaMatches should check type sub-schema of control via predicate', (t) => { const schema: JsonSchema = { type: 'object',