refactor(helper-plugin): extract params based on error type

test(helper-plugin): getYupInnerErrors
This commit is contained in:
Jamie Howard 2023-02-10 11:48:02 +00:00
parent d4e111a027
commit 6d5fd07184
2 changed files with 34 additions and 10 deletions

View File

@ -1,24 +1,24 @@
/** /**
* Extract relevant values from the Yup error that can be used to enhance front * Extract relevant values from the Yup error that can be used to enhance front
* end error messaging * end error messaging
* @param {Object} yupErrorParams * @param {String} errorType
* @returns {Object} * @param {Object} errorParams
* @returns {Object} values to pass to error translation string
*/ */
const extractValuesFromYupError = (yupErrorParams = {}) => const extractValuesFromYupError = (errorType, errorParams = {}) =>
Object.keys(yupErrorParams) Object.keys(errorParams)
.filter((key) => !['label', 'originalValue', 'path', 'value'].includes(key)) .filter((key) => errorType === key)
.reduce((current, key) => Object.assign(current, { [key]: yupErrorParams[key] }), {}); .reduce((current, key) => Object.assign(current, { [key]: errorParams[key] }), {});
const getYupInnerErrors = (error) => { const getYupInnerErrors = (error) =>
return (error?.inner || []).reduce((acc, currentError) => { (error?.inner || []).reduce((acc, currentError) => {
acc[currentError.path.split('[').join('.').split(']').join('')] = { acc[currentError.path.split('[').join('.').split(']').join('')] = {
id: currentError.message, id: currentError.message,
defaultMessage: currentError.message, defaultMessage: currentError.message,
values: extractValuesFromYupError(currentError?.params || {}), values: extractValuesFromYupError(currentError.type, currentError?.params || {}),
}; };
return acc; return acc;
}, {}); }, {});
};
export default getYupInnerErrors; export default getYupInnerErrors;

View File

@ -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 },
},
});
});
});