Skip to content

Commit

Permalink
feat: add hasOption tester
Browse files Browse the repository at this point in the history
Adds the new "hasOption" util to check for the existence of an option.
  • Loading branch information
zaosoula committed Feb 19, 2024
1 parent 072caa5 commit 51b63f5
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
18 changes: 18 additions & 0 deletions packages/core/src/testers/testers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -215,6 +216,23 @@ 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.
*
Expand Down
25 changes: 25 additions & 0 deletions packages/core/test/testers.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ import {
JsonSchema,
LabelElement,
UISchemaElement,
hasOption,
} from '../src';

const test = anyTest as TestInterface<{ uischema: ControlElement }>;
Expand Down Expand Up @@ -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',
Expand Down

0 comments on commit 51b63f5

Please sign in to comment.