diff --git a/src/components/Select/__tests__/getSelectedOptionsContent.test.ts b/src/components/Select/__tests__/getSelectedOptionsContent.test.ts new file mode 100644 index 000000000..e7bfba5a9 --- /dev/null +++ b/src/components/Select/__tests__/getSelectedOptionsContent.test.ts @@ -0,0 +1,53 @@ +import {getSelectedOptionsContent} from '../utils'; + +const options = [ + {value: 'val1', content: 'content1'}, + {value: 'val2', content: 'content2'}, +]; + +const presenceValue = ['val1']; +const notPresenceValue = ['val3']; + +describe('getSelectedOptionsContent', () => { + describe('default appearance', () => { + test('option presence. Should return content', async () => { + const result = getSelectedOptionsContent(options, presenceValue); + + expect(result).toEqual('content1'); + }); + test('option NOT presence. Should return value', async () => { + const result = getSelectedOptionsContent(options, notPresenceValue); + + expect(result).toEqual('val3'); + }); + test('some of option NOT presence. Should return value', async () => { + const result = getSelectedOptionsContent(options, [ + ...presenceValue, + ...notPresenceValue, + ]); + + expect(result).toEqual('content1, val3'); + }); + }); + describe('renderSelectedOption callback', () => { + const renderSelectedOptionPostfix = 'from callback'; + const renderSelectedOption = jest.fn( + (opt) => `${opt.content || opt.value}${renderSelectedOptionPostfix}` as any, + ); + + test('option presence. Should be called with option', async () => { + renderSelectedOption.mockClear(); + getSelectedOptionsContent(options, presenceValue, renderSelectedOption); + + expect(renderSelectedOption).toBeCalledTimes(1); + expect(renderSelectedOption).toBeCalledWith(options[0], 0); + }); + test('option NOT presence. Should be called with generated object', async () => { + renderSelectedOption.mockClear(); + getSelectedOptionsContent(options, notPresenceValue, renderSelectedOption); + + expect(renderSelectedOption).toBeCalledTimes(1); + expect(renderSelectedOption).toBeCalledWith({value: notPresenceValue[0]}, 0); + }); + }); +}); diff --git a/src/components/Select/utils.tsx b/src/components/Select/utils.tsx index 679dda291..7748d1219 100644 --- a/src/components/Select/utils.tsx +++ b/src/components/Select/utils.tsx @@ -85,17 +85,14 @@ export const getSelectedOptionsContent = ( return null; } - const selectedOptions = flattenOptions.reduce((acc, option) => { - if ('label' in option) { - return acc; - } - - const optionSelected = value.includes(option.value); + const flattenSimpleOptions = flattenOptions.filter( + (opt) => !('label' in opt), + ) as SelectOption[]; - if (optionSelected) { - acc.push(option); - } + const selectedOptions = value.reduce((acc, val) => { + const selectedOption = flattenSimpleOptions.find((opt) => opt.value === val); + acc.push(selectedOption || {value: val}); return acc; }, [] as SelectOption[]);