Skip to content

Commit

Permalink
fix(angular): throw an error when generating a component and the spec…
Browse files Browse the repository at this point in the history
…ified module can't be found (#19324)
  • Loading branch information
leosvelperez authored Sep 25, 2023
1 parent 295ea3f commit 312351b
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 5 deletions.
31 changes: 31 additions & 0 deletions packages/angular/src/generators/component/component.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -781,6 +781,37 @@ describe('component Generator', () => {
`);
});

it('should throw an error when the module is not found', 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 {}`
);

// ACT & ASSERT
await expect(
componentGenerator(tree, {
name: 'example',
project: 'lib1',
path: 'libs/lib1/src/lib',
module: 'not-found',
})
).rejects.toThrow();
});

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' });
Expand Down
14 changes: 9 additions & 5 deletions packages/angular/src/generators/component/lib/module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,16 @@ import { joinPathFragments, normalizePath } from '@nx/devkit';
import { basename, dirname } from 'path';
import type { NormalizedSchema } from '../schema';

// Adapted from https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/utility/find-module.ts#L29
// to match the logic in the component schematic. It doesn't throw if it can't
// find a module since the schematic would have thrown before getting here.
// Adapted from https://github.com/angular/angular-cli/blob/732aab5fa7e63618c89dfbbb6f78753f706d7014/packages/schematics/angular/utility/find-module.ts#L29
// to match the logic from the Angular CLI component schematic.
const moduleExt = '.module.ts';
const routingModuleExt = '-routing.module.ts';

export function findModuleFromOptions(
tree: Tree,
options: NormalizedSchema,
projectRoot: string
): string | null {
): string {
if (!options.module) {
return normalizePath(findModule(tree, options.directory, projectRoot));
} else {
Expand Down Expand Up @@ -49,7 +48,12 @@ export function findModuleFromOptions(
}
}

return null;
throw new Error(
`Specified module '${options.module}' does not exist.\n` +
`Looked in the following directories:\n ${candidatesDirs.join(
'\n '
)}`
);
}
}

Expand Down

0 comments on commit 312351b

Please sign in to comment.