diff --git a/packages/core/helper-plugin/lib/src/utils/getYupInnerErrors/index.js b/packages/core/helper-plugin/lib/src/utils/getYupInnerErrors/index.js index c67fe0f889..705b4c2e36 100644 --- a/packages/core/helper-plugin/lib/src/utils/getYupInnerErrors/index.js +++ b/packages/core/helper-plugin/lib/src/utils/getYupInnerErrors/index.js @@ -1,24 +1,24 @@ /** * Extract relevant values from the Yup error that can be used to enhance front * end error messaging - * @param {Object} yupErrorParams - * @returns {Object} + * @param {String} errorType + * @param {Object} errorParams + * @returns {Object} values to pass to error translation string */ -const extractValuesFromYupError = (yupErrorParams = {}) => - Object.keys(yupErrorParams) - .filter((key) => !['label', 'originalValue', 'path', 'value'].includes(key)) - .reduce((current, key) => Object.assign(current, { [key]: yupErrorParams[key] }), {}); +const extractValuesFromYupError = (errorType, errorParams = {}) => + Object.keys(errorParams) + .filter((key) => errorType === key) + .reduce((current, key) => Object.assign(current, { [key]: errorParams[key] }), {}); -const getYupInnerErrors = (error) => { - return (error?.inner || []).reduce((acc, currentError) => { +const getYupInnerErrors = (error) => + (error?.inner || []).reduce((acc, currentError) => { acc[currentError.path.split('[').join('.').split(']').join('')] = { id: currentError.message, defaultMessage: currentError.message, - values: extractValuesFromYupError(currentError?.params || {}), + values: extractValuesFromYupError(currentError.type, currentError?.params || {}), }; return acc; }, {}); -}; export default getYupInnerErrors; diff --git a/packages/core/helper-plugin/lib/src/utils/getYupInnerErrors/tests/index.test.js b/packages/core/helper-plugin/lib/src/utils/getYupInnerErrors/tests/index.test.js new file mode 100644 index 0000000000..785bd8b9da --- /dev/null +++ b/packages/core/helper-plugin/lib/src/utils/getYupInnerErrors/tests/index.test.js @@ -0,0 +1,24 @@ +import getYupInnerErrors from '../index'; + +describe('getYupInnerErrors', () => { + test('can extract relevant parameters from an error', () => { + const maxError = { + inner: [ + { + path: 'Name', + type: 'max', + params: { max: 5 }, + message: 'components.Input.error.validation.maxLength', + }, + ], + }; + + expect(getYupInnerErrors(maxError)).toMatchObject({ + Name: { + id: 'components.Input.error.validation.maxLength', + defaultMessage: 'components.Input.error.validation.maxLength', + values: { max: 5 }, + }, + }); + }); +});