Skip to content

Commit 51b63f5

Browse files
authored
feat: add hasOption tester
Adds the new "hasOption" util to check for the existence of an option.
1 parent 072caa5 commit 51b63f5

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

packages/core/src/testers/testers.ts

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ import isArray from 'lodash/isArray';
3131
import reduce from 'lodash/reduce';
3232
import toPairs from 'lodash/toPairs';
3333
import includes from 'lodash/includes';
34+
import isUndefined from 'lodash/isUndefined';
3435
import type {
3536
Categorization,
3637
ControlElement,
@@ -215,6 +216,23 @@ export const optionIs =
215216
return !isEmpty(options) && options[optionName] === optionValue;
216217
};
217218

219+
/**
220+
* Checks whether the given UI schema has an option with the given
221+
* name. If no options property is set, returns false.
222+
*
223+
* @param {string} optionName the name of the option to check
224+
*/
225+
export const hasOption =
226+
(optionName: string): Tester =>
227+
(uischema: UISchemaElement): boolean => {
228+
if (isEmpty(uischema)) {
229+
return false;
230+
}
231+
232+
const options = uischema.options;
233+
return !isEmpty(options) && !isUndefined(options[optionName]);
234+
};
235+
218236
/**
219237
* Only applicable for Controls.
220238
*

packages/core/test/testers.test.ts

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,7 @@ import {
5454
JsonSchema,
5555
LabelElement,
5656
UISchemaElement,
57+
hasOption,
5758
} from '../src';
5859

5960
const test = anyTest as TestInterface<{ uischema: ControlElement }>;
@@ -183,6 +184,30 @@ test('optionIs should return false for UI schema elements without options cell',
183184
t.false(optionIs('answer', 42)(control, undefined, undefined));
184185
});
185186

187+
test('hasOption should check for options', (t) => {
188+
const control: ControlElement = {
189+
type: 'Control',
190+
scope: '#/properties/bar',
191+
options: {
192+
answer: 42,
193+
},
194+
};
195+
t.true(hasOption('answer')(control, undefined, undefined));
196+
});
197+
198+
test('hasOption should not fail if uischema is undefined or null', (t) => {
199+
const uischema: UISchemaElement = null;
200+
t.false(hasOption('answer')(uischema, undefined, undefined));
201+
});
202+
203+
test('hasOption should return false for UI schema elements without options cell', (t) => {
204+
const control: ControlElement = {
205+
type: 'Control',
206+
scope: '#/properties/bar',
207+
};
208+
t.false(hasOption('answer')(control, undefined, undefined));
209+
});
210+
186211
test('schemaMatches should check type sub-schema of control via predicate', (t) => {
187212
const schema: JsonSchema = {
188213
type: 'object',

0 commit comments

Comments
 (0)