From 36d8403a24c67d90c38606044102f11080164389 Mon Sep 17 00:00:00 2001 From: Georgii Karataev Date: Thu, 23 Nov 2023 15:41:44 +0100 Subject: [PATCH] fix(ESSNTL-5418): Trim group name before validate (#2105) Fixes https://issues.redhat.com/browse/ESSNTL-5418. --- .../Modals/CreateGroupModal.js | 23 +++++++++-------- .../Modals/CreateGroupModal.test.js | 25 +++++++++++++++++++ 2 files changed, 37 insertions(+), 11 deletions(-) create mode 100644 src/components/InventoryGroups/Modals/CreateGroupModal.test.js diff --git a/src/components/InventoryGroups/Modals/CreateGroupModal.js b/src/components/InventoryGroups/Modals/CreateGroupModal.js index 7e3a5bd4d..87458538c 100644 --- a/src/components/InventoryGroups/Modals/CreateGroupModal.js +++ b/src/components/InventoryGroups/Modals/CreateGroupModal.js @@ -7,6 +7,15 @@ import { createGroup, validateGroupName } from '../utils/api'; import { useDispatch } from 'react-redux'; import awesomeDebouncePromise from 'awesome-debounce-promise'; +export const validate = async (value) => { + const results = await validateGroupName(value.trim()); + if (results === true) { + throw 'Group name already exists'; + } + + return undefined; +}; + const CreateGroupModal = ({ isModalOpen, setIsModalOpen, @@ -31,17 +40,9 @@ const CreateGroupModal = ({ ); const schema = useMemo(() => { - const check = async (value) => { - const results = await validateGroupName(value); - if (results === true) { - throw 'Group name already exists'; - } - - return undefined; - }; - - // eslint-disable-next-line new-cap - const d = awesomeDebouncePromise(check, 500, { onlyResolvesLast: false }); + const d = awesomeDebouncePromise(validate, 500, { + onlyResolvesLast: false, + }); return createGroupSchema(d); }, []); diff --git a/src/components/InventoryGroups/Modals/CreateGroupModal.test.js b/src/components/InventoryGroups/Modals/CreateGroupModal.test.js new file mode 100644 index 000000000..9ae4a7ad0 --- /dev/null +++ b/src/components/InventoryGroups/Modals/CreateGroupModal.test.js @@ -0,0 +1,25 @@ +import { validateGroupName } from '../utils/api'; +import { validate } from './CreateGroupModal'; + +jest.mock('../utils/api'); + +describe('validate function', () => { + it('works with basic input', async () => { + const result = await validate('test'); + + expect(result).toBe(undefined); + expect(validateGroupName).toHaveBeenCalledWith('test'); + }); + + it('trims input', async () => { + const result = await validate(' test '); + + expect(result).toBe(undefined); + expect(validateGroupName).toHaveBeenCalledWith('test'); + }); + + it('throws error if the name is present', async () => { + validateGroupName.mockResolvedValue(true); + await expect(validate('test')).rejects.toBe('Group name already exists'); + }); +});