From f6418d724a9f82830d90f64c2aced9c0ba00f451 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9=20Andersson?= Date: Fri, 12 Apr 2024 10:55:27 +0200 Subject: [PATCH] fix: unable to find instance in case of ng17 control flow ViewContainerRef actually returns the wrong length in case of Angular 17 Control Flow. By checking that the returned value is not null we should be safe. Solves #7216 --- .../mock-helper/crawl/el-def-get-parent.ts | 4 ++ tests/issue-7216/test.spec.ts | 47 +++++++++++++++++++ 2 files changed, 51 insertions(+) create mode 100644 tests/issue-7216/test.spec.ts diff --git a/libs/ng-mocks/src/lib/mock-helper/crawl/el-def-get-parent.ts b/libs/ng-mocks/src/lib/mock-helper/crawl/el-def-get-parent.ts index 45664ab3cb..519ba2ede6 100644 --- a/libs/ng-mocks/src/lib/mock-helper/crawl/el-def-get-parent.ts +++ b/libs/ng-mocks/src/lib/mock-helper/crawl/el-def-get-parent.ts @@ -24,6 +24,10 @@ const getScanViewRefRootNodes = (node: any, child: any): Array<[number, any]> => const result: Array<[number, any]> = []; for (let vrIndex = 0; vrIndex < vcr.length; vrIndex += 1) { const vr = vcr.get(vrIndex); + if (!vr) { + continue; + } + for (let rnIndex = 0; rnIndex < (vr as any).rootNodes.length; rnIndex += 1) { result.push([rnIndex, (vr as any).rootNodes[rnIndex]]); } diff --git a/tests/issue-7216/test.spec.ts b/tests/issue-7216/test.spec.ts new file mode 100644 index 0000000000..366ddc6654 --- /dev/null +++ b/tests/issue-7216/test.spec.ts @@ -0,0 +1,47 @@ +import { CommonModule } from '@angular/common'; +import { Component, NgModule, VERSION } from '@angular/core'; + +import { MockBuilder, MockRender, ngMocks } from 'ng-mocks'; + +// @see /~https://github.com/help-me-mom/ng-mocks/issues/7216 +describe('issue-7216', () => { + if (Number.parseInt(VERSION.major, 10) < 17) { + it('needs a17+', () => { + expect(true).toBeTruthy(); + }); + + return; + } + + @Component({ + selector: 'target', + template: ` + @if (hasChild) { + + } + `, + }) + class TargetComponent { + public readonly hasChild = true; + } + + @Component({ + selector: 'child', + template: '', + }) + class ChildComponent {} + + @NgModule({ + imports: [CommonModule], + declarations: [TargetComponent, ChildComponent], + }) + class TargetModule {} + + beforeEach(() => MockBuilder(TargetComponent, TargetModule)); + + it('finds child-element', () => { + MockRender(TargetComponent); + + expect(ngMocks.findInstance(ChildComponent)).toBeTruthy(); + }); +});