Skip to content

Commit

Permalink
fix: unable to find instance in case of ng17 control flow
Browse files Browse the repository at this point in the history
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
  • Loading branch information
André Andersson committed Apr 12, 2024
1 parent 905f882 commit f6418d7
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
4 changes: 4 additions & 0 deletions libs/ng-mocks/src/lib/mock-helper/crawl/el-def-get-parent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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]]);
}
Expand Down
47 changes: 47 additions & 0 deletions tests/issue-7216/test.spec.ts
Original file line number Diff line number Diff line change
@@ -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) {
<child></child>
}
`,
})
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();
});
});

0 comments on commit f6418d7

Please sign in to comment.