Skip to content

Commit

Permalink
Add unit tests for getField()
Browse files Browse the repository at this point in the history
  • Loading branch information
skh committed Mar 18, 2020
1 parent 36fdca0 commit b5a3ad7
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { readFileSync } from 'fs';
import glob from 'glob';
import { safeLoad } from 'js-yaml';
import path from 'path';
import { Field, processFields } from './field';
import { Field, Fields, getField, processFields } from './field';

// Add our own serialiser to just do JSON.stringify
expect.addSnapshotSerializer({
Expand All @@ -33,3 +33,50 @@ test('tests loading fields.yml', () => {
expect(processedFields).toMatchSnapshot(path.basename(file));
}
});

describe('getField searches recursively for nested field in fields given an array of path parts', () => {
const searchFields: Fields = [
{
name: '1',
fields: [
{
name: '1-1',
},
{
name: '1-2',
},
],
},
{
name: '2',
fields: [
{
name: '2-1',
},
{
name: '2-2',
fields: [
{
name: '2-2-1',
},
{
name: '2-2-2',
},
],
},
],
},
];
test('returns undefined when the field does not exist', () => {
expect(getField(searchFields, ['0'])).toBe(undefined);
});
test('returns undefined if the field is not a leaf node', () => {
expect(getField(searchFields, ['1'])?.name).toBe(undefined);
});
test('returns undefined searching for a nested field that does not exist', () => {
expect(getField(searchFields, ['1', '1-3'])?.name).toBe(undefined);
});
test('returns nested field that is a leaf node', () => {
expect(getField(searchFields, ['2', '2-2', '2-2-1'])?.name).toBe('2-2-1');
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ function validateAliasFields(fields: Fields, allFields: Fields): Fields {
return validatedFields;
}

const getField = (fields: Fields, pathNames: string[]): Field | undefined => {
export const getField = (fields: Fields, pathNames: string[]): Field | undefined => {
if (!pathNames.length) return undefined;
// get the first rest of path names
const [name, ...restPathNames] = pathNames;
Expand Down

0 comments on commit b5a3ad7

Please sign in to comment.