From 48b356d9c1c791aaaf0f5d2898905e99675f66d7 Mon Sep 17 00:00:00 2001 From: Colum Ferry Date: Wed, 19 Apr 2023 09:46:13 +0100 Subject: [PATCH] fix(angular): throw error when generating component with multiple candidate modules (#16332) --- .../generators/component/component.spec.ts | 41 +++++++++++++++++++ .../src/generators/component/lib/module.ts | 4 +- 2 files changed, 44 insertions(+), 1 deletion(-) diff --git a/packages/angular/src/generators/component/component.spec.ts b/packages/angular/src/generators/component/component.spec.ts index 1cae01a176f34..ac9b481e7f043 100644 --- a/packages/angular/src/generators/component/component.spec.ts +++ b/packages/angular/src/generators/component/component.spec.ts @@ -735,6 +735,47 @@ describe('component Generator', () => { " `); }); + + it('should throw an error when there are more than one candidate modules that the component can be added to', async () => { + // ARRANGE + const tree = createTreeWithEmptyWorkspace({ layout: 'apps-libs' }); + addProjectConfiguration(tree, 'lib1', { + projectType: 'library', + sourceRoot: 'libs/lib1/src', + root: 'libs/lib1', + }); + tree.write( + 'libs/lib1/src/lib/lib.module.ts', + ` + import { NgModule } from '@angular/core'; + + @NgModule({ + declarations: [], + exports: [] + }) + export class LibModule {}` + ); + tree.write( + 'libs/lib1/src/lib/lib2.module.ts', + ` + import { NgModule } from '@angular/core'; + + @NgModule({ + declarations: [], + exports: [] + }) + export class Lib2Module {}` + ); + + // ACT & ASSERT + await expect( + componentGenerator(tree, { + name: 'example', + project: 'lib1', + path: 'libs/lib1/src/lib', + }) + ).rejects.toThrow(); + }); }); describe('secondary entry points', () => { diff --git a/packages/angular/src/generators/component/lib/module.ts b/packages/angular/src/generators/component/lib/module.ts index 97164560f71e4..8b5b665e355e2 100644 --- a/packages/angular/src/generators/component/lib/module.ts +++ b/packages/angular/src/generators/component/lib/module.ts @@ -72,7 +72,9 @@ function findModule( if (filteredMatches.length == 1) { return filteredMatches[0]; } else if (filteredMatches.length > 1) { - return null; + throw new Error( + "Found more than one candidate module to add the component to. Please specify which module the component should be added to by using the '--module' option." + ); } dir = dirname(dir);