Skip to content
Snippets Groups Projects
Commit ee1025c5 authored by Jan Zickermann's avatar Jan Zickermann
Browse files

OZG-4949 Implement `setInvalidParamValidationError`

parent be2f1a06
No related branches found
No related tags found
No related merge requests found
...@@ -21,25 +21,18 @@ ...@@ -21,25 +21,18 @@
* Die sprachspezifischen Genehmigungen und Beschränkungen * Die sprachspezifischen Genehmigungen und Beschränkungen
* unter der Lizenz sind dem Lizenztext zu entnehmen. * unter der Lizenz sind dem Lizenztext zu entnehmen.
*/ */
import { import { AbstractControl, FormControl, FormGroup, UntypedFormControl, UntypedFormGroup } from '@angular/forms';
AbstractControl, import { createInvalidParam, createIssue } from '../../../test/error';
FormControl,
FormGroup,
UntypedFormControl,
UntypedFormGroup,
} from '@angular/forms';
import { createIssue } from '../../../test/error';
import { InvalidParam, Issue } from '../tech.model'; import { InvalidParam, Issue } from '../tech.model';
import { import {
getControlForIssue, getControlForIssue,
getMessageForInvalidParam, getMessageForInvalidParam,
getMessageForIssue, getMessageForIssue,
setInvalidParamValidationError,
setIssueValidationError, setIssueValidationError,
} from './tech.validation.util'; } from './tech.validation.util';
import { ValidationMessageCode } from './tech.validation.messages';
describe('ValidationUtils', () => { describe('ValidationUtils', () => {
describe('set issue validation error', () => {
const baseField1Control: FormControl = new UntypedFormControl(); const baseField1Control: FormControl = new UntypedFormControl();
const baseField2Control: FormControl = new UntypedFormControl(); const baseField2Control: FormControl = new UntypedFormControl();
const subGroupFieldControl: FormControl = new UntypedFormControl(); const subGroupFieldControl: FormControl = new UntypedFormControl();
...@@ -52,6 +45,7 @@ describe('ValidationUtils', () => { ...@@ -52,6 +45,7 @@ describe('ValidationUtils', () => {
}), }),
}); });
describe('set issue validation error', () => {
describe('get control for issue', () => { describe('get control for issue', () => {
it('should return base field control', () => { it('should return base field control', () => {
const issue: Issue = { ...createIssue(), field: 'baseField1' }; const issue: Issue = { ...createIssue(), field: 'baseField1' };
...@@ -149,81 +143,97 @@ describe('ValidationUtils', () => { ...@@ -149,81 +143,97 @@ describe('ValidationUtils', () => {
}); });
}); });
describe('get message for invalid-params-item', () => { describe('getMessageForInvalidParam', () => {
const item: InvalidParam = { it('should return message', () => {
name: 'name-of-field', const invalidParam: InvalidParam = createInvalidParam();
reason: ValidationMessageCode.VALIDATION_FIELD_EMPTY,
const msg: string = getMessageForInvalidParam(invalidParam);
expect(msg).toEqual(`Bitte ${invalidParam.name} ausfüllen`);
});
});
describe('setInvalidParamValidationError', () => {
const formPrefixes = ['', 'some-prefix'];
const fieldNames = ['baseField1', 'baseField2', 'subGroup.subGroupField1'];
const prefixNameCombinations = formPrefixes.flatMap((prefix) =>
fieldNames.map((name) => [prefix, name]),
);
const unknownName = 'unknown-field';
describe.each(prefixNameCombinations)(
'with prefix "%s" and fieldName "%s"',
(prefix, fieldName) => {
let invalidParam: InvalidParam;
let invalidParamWithoutPrefix: InvalidParam;
beforeEach(() => {
form.reset();
invalidParamWithoutPrefix = createInvalidParam();
invalidParamWithoutPrefix.name = fieldName;
invalidParam = {
reason: invalidParamWithoutPrefix.reason,
name: prefix.length ? `${prefix}.${fieldName}` : fieldName,
}; };
});
it('should return message', () => { it('should assign invalidParam to form control error without prefix', () => {
const msg: string = getMessageForInvalidParam(item); const message = getMessageForInvalidParam(invalidParamWithoutPrefix);
expect(msg).toEqual(`Bitte ${item.name} ausfüllen`); setInvalidParamValidationError(form, invalidParam, prefix);
});
}); const errorMessage = form.getError(invalidParam.reason, fieldName);
}); expect(errorMessage).toBe(message);
});
// describe('setValidationDetails', () => {
// let form: UntypedFormGroup; it('should mark form as touched', () => {
// const fieldName = 'test-field'; setInvalidParamValidationError(form, invalidParam, prefix);
// beforeEach(() => { expect(form.touched).toBeTruthy();
// form = formService.form; });
// const control = new FormControl(''); },
// form.addControl(fieldName, control); );
// });
describe.each([
// it('should set invalid-params of validation-problem-details on control', () => { ['', '', 'unknown-field'],
// const validationDetails: ProblemDetail = createAbsenderNameProblemDetail(); ['valid-prefix', 'valid-prefix', 'unknown-field'],
// const item = validationDetails['invalid-params'][0]; ['valid-prefix', 'valid-prefix', 'unknown-field'],
// item.name = '.' + fieldName; ['unknown-prefix', 'valid-prefix', 'unknown-field'],
['unknown-prefix', 'valid-prefix', 'baseField1'],
// formService.setErrorByProblemDetail(validationDetails); ])(
'with pathPrefix "%s", paramPrefix "%s", and field-name "%s"',
// const itemError = form.getError(item.reason, fieldName); (pathPrefix, paramPrefix, fieldName) => {
// expect(itemError).toBe( let invalidParam: InvalidParam;
// getMessageForInvalidParamsItem({
// ...item, beforeEach(() => {
// name: fieldName, form.reset();
// }), invalidParam = createInvalidParam();
// ); invalidParam.name = paramPrefix.length > 0 ? `${paramPrefix}.${fieldName}` : fieldName;
// }); });
// });
it('should not assign to field control error', () => {
// describe('set error by api error', () => { setInvalidParamValidationError(form, invalidParam, pathPrefix);
// // let form: UntypedFormGroup;
// const fieldName: string = 'test-field'; const errorMessage = form.getError(invalidParam.reason, unknownName);
expect(errorMessage).toBeFalsy();
// beforeEach(() => { });
// // form = formService.form;
// // const control = ; it('should not mark as touched', () => {
// formService.form.addControl(fieldName, new FormControl('')); setInvalidParamValidationError(form, invalidParam, pathPrefix);
// });
expect(form.touched).toBeFalsy();
// it('should set issues of api-error on control', () => { });
// const issue: Issue = { ...createIssue(), field: TestFormService + '.' + fieldName }; },
// const apiError: ApiError = createApiError([issue]); );
// formService.setErrorByApiError(apiError); it('should not assign invalidParam with incorrect prefix', () => {
const invalidParam: InvalidParam = createInvalidParam();
// expect(formService.form.getError(issue.messageCode, fieldName)).toBe(issue); invalidParam.name = `correct-prefix.baseField1`;
// });
// }); setInvalidParamValidationError(form, invalidParam, 'incorrect-prefix');
// export function createAbsenderNameProblemDetail(invalidParams: InvalidParam[]): ProblemDetail { const errorMessage = form.getError(invalidParam.reason, unknownName);
// return { expect(errorMessage).toBeFalsy();
// type: 'about:blank', });
// title: 'Unprocessable Entity', });
// status: HttpStatusCode.UnprocessableEntity, });
// detail: 'settingsBody.absender.name: validation_field_empty',
// instance: '/api/configuration/settings/65df039a69eeafef365a42dd',
// 'invalid-params': invalidParams,
// };
// }
// export function createAbsenderNameInvalidParam(): InvalidParam {
// return {
// name: 'settingsBody.absender.name',
// reason: ValidationMessageCode.VALIDATION_FIELD_EMPTY,
// };
// }
...@@ -21,10 +21,10 @@ ...@@ -21,10 +21,10 @@
* Die sprachspezifischen Genehmigungen und Beschränkungen * Die sprachspezifischen Genehmigungen und Beschränkungen
* unter der Lizenz sind dem Lizenztext zu entnehmen. * unter der Lizenz sind dem Lizenztext zu entnehmen.
*/ */
import { AbstractControl, FormGroup, UntypedFormGroup } from '@angular/forms'; import { AbstractControl, UntypedFormGroup } from '@angular/forms';
import { isNil } from 'lodash-es'; import { isNil } from 'lodash-es';
import { ApiError, InvalidParam, Issue, IssueParam } from '../tech.model'; import { ApiError, InvalidParam, Issue, IssueParam } from '../tech.model';
import { replacePlaceholder } from '../tech.util'; import { isNotNil, replacePlaceholder } from '../tech.util';
import { VALIDATION_MESSAGES, ValidationMessageCode } from './tech.validation.messages'; import { VALIDATION_MESSAGES, ValidationMessageCode } from './tech.validation.messages';
export function isValidationError(issue: Issue): boolean { export function isValidationError(issue: Issue): boolean {
...@@ -80,47 +80,25 @@ export function getMessageCode(apiError: ApiError): string { ...@@ -80,47 +80,25 @@ export function getMessageCode(apiError: ApiError): string {
return apiError.issues[0].messageCode; return apiError.issues[0].messageCode;
} }
//TODO TDD entwickeln - kleine Tests
export function setInvalidParamValidationError( export function setInvalidParamValidationError(
form: UntypedFormGroup, form: UntypedFormGroup,
invalidParam: InvalidParam, invalidParam: InvalidParam,
pathPrefix?: string, pathPrefix: string = '',
): void { ): void {
const item: InvalidParam = itemWithoutNamePrefix(invalidParam, pathPrefix); const item: InvalidParam = mapInvalidParamWithoutPrefix(invalidParam, pathPrefix);
const formControl: AbstractControl = form.get(item.name); const formControl: AbstractControl = form.get(item.name);
if (isNotNil(formControl)) {
formControl.setErrors({ [item.reason]: getMessageForInvalidParam(item) }); formControl.setErrors({ [item.reason]: getMessageForInvalidParam(item) });
formControl.markAsTouched(); formControl.markAsTouched();
} }
}
//Das Verb fehlt bei der Function function mapInvalidParamWithoutPrefix(item: InvalidParam, pathPrefix: string): InvalidParam {
function itemWithoutNamePrefix(item: InvalidParam, pathPrefix?: string): InvalidParam { return pathPrefix.length > 0 ?
const namePath: string = item.name; { ...item, name: item.name.substring(pathPrefix.length + 1) }
//Was wird hier genau gemacht? warum? : item;
const pathPrefixIrgendwas: string = pathPrefix + (pathPrefix.endsWith('.') ? '' : '.');
//Der pathPrefix wird doch einmal konfiguriert und dann sollte das doch passen, wann und warum genau soll hier der Error geworfen werden?
if (!namePath.startsWith(pathPrefix))
throw Error(`Expected prefix ${pathPrefix} not found: ${namePath}`);
//Ich finde das sehr merkwürdig, dass hier was im Item manipuliert und dann zurückgegeben wird, wieso nicht einfach den name zurückgeben?
return { ...item, name: namePath.substring(pathPrefixIrgendwas.length) };
} }
export function getMessageForInvalidParam(item: InvalidParam): string { export function getMessageForInvalidParam(item: InvalidParam): string {
let formatString: string = VALIDATION_MESSAGES[item.reason] ?? item.reason; return replacePlaceholder(VALIDATION_MESSAGES[item.reason], 'field', item.name);
//Wieso wird hier durchiteriert? Das ist doch ein Item mit name und reason oder nicht?
for (const [itemField, value] of Object.entries(item)) {
//Warum genau wird "das" hier aufgebaut?
const itemFieldToPlaceholder = {
name: 'field',
};
formatString = replacePlaceholder(
formatString,
//Verstehe ich auch nicht, wieso nicht einfach 'field'?
itemFieldToPlaceholder[itemField] ?? itemField,
value,
);
}
return formatString;
} }
//
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment