From 600d266ca4ea478f8f23664140cdb4c2db26d74c Mon Sep 17 00:00:00 2001 From: Alan Agius Date: Thu, 27 May 2021 09:40:40 +0200 Subject: [PATCH] fix(@angular-devkit/core): show allowed enum values when validation on enum fails --- .../core/src/json/schema/registry.ts | 12 +++++++-- .../core/src/json/schema/registry_spec.ts | 27 ++++++++++++++++++- 2 files changed, 36 insertions(+), 3 deletions(-) diff --git a/packages/angular_devkit/core/src/json/schema/registry.ts b/packages/angular_devkit/core/src/json/schema/registry.ts index f022eb156261..2939d91d4802 100644 --- a/packages/angular_devkit/core/src/json/schema/registry.ts +++ b/packages/angular_devkit/core/src/json/schema/registry.ts @@ -63,8 +63,16 @@ export class SchemaValidationException extends BaseException { const messages = errors.map((err) => { let message = `Data path ${JSON.stringify(err.instancePath)} ${err.message}`; - if (err.keyword === 'additionalProperties') { - message += `(${err.params.additionalProperty})`; + switch (err.keyword) { + case 'additionalProperties': + message += `(${err.params.additionalProperty})`; + break; + + case 'enum': + message += `. Allowed values are: ${(err.params.allowedValues as string[] | undefined) + ?.map((v) => `"${v}"`) + .join(', ')}`; + break; } return message + '.'; diff --git a/packages/angular_devkit/core/src/json/schema/registry_spec.ts b/packages/angular_devkit/core/src/json/schema/registry_spec.ts index 84b85eb91ae8..2ce888f74f9e 100644 --- a/packages/angular_devkit/core/src/json/schema/registry_spec.ts +++ b/packages/angular_devkit/core/src/json/schema/registry_spec.ts @@ -9,7 +9,7 @@ /* eslint-disable @typescript-eslint/no-explicit-any */ import { map, mergeMap } from 'rxjs/operators'; import { SchemaFormat } from './interface'; -import { CoreSchemaRegistry } from './registry'; +import { CoreSchemaRegistry, SchemaValidationException } from './registry'; import { addUndefinedDefaults } from './transforms'; describe('CoreSchemaRegistry', () => { @@ -138,6 +138,31 @@ describe('CoreSchemaRegistry', () => { .then(done, done.fail); }); + it('fails on invalid enum value', (done) => { + const registry = new CoreSchemaRegistry(); + registry.addPostTransform(addUndefinedDefaults); + const data = { packageManager: 'foo' }; + + registry + .compile({ + properties: { + packageManager: { type: 'string', enum: ['npm', 'yarn', 'pnpm', 'cnpm'] }, + }, + additionalProperties: false, + }) + .pipe( + mergeMap((validator) => validator(data)), + map((result) => { + expect(result.success).toBe(false); + expect(new SchemaValidationException(result.errors).message).toContain( + `Data path "/packageManager" must be equal to one of the allowed values. Allowed values are: "npm", "yarn", "pnpm", "cnpm".`, + ); + }), + ) + .toPromise() + .then(done, done.fail); + }); + it('fails on invalid additionalProperties async', (done) => { const registry = new CoreSchemaRegistry(); registry.addPostTransform(addUndefinedDefaults);