spectator icon indicating copy to clipboard operation
spectator copied to clipboard

Being able to query for component instances within a selector.

Open undsoft opened this issue 2 years ago • 1 comments

Description

Given the following component dom:

<div class="group1">
  <muh-component></muh-component>
  <muh-component></muh-component>
</div>
<div class="group2">
  <muh-component></muh-component>
  <muh-component></muh-component>
</div>

There does not seem to exist a concise way to query for component instances within a group of MuhComponent using spectator.query(MuhComponent). I can query for all of them, but not within a group.

In my particular case, I'm mocking MuhComponent with ng-mocks and I am trying to access it's @Input().

Proposed solution

Have some sort of way to add selector, for example:

spectator.queryAll(MuhComponent, { within: '.group1' });

Alternatives considered

I can do something similar with harnesses, but I don't know how to get component's input (also can't mock the component).

Alternatively I think I can do:

const elements = spectator.debugElement.query(By.css('.group1')).queryAll(By.directive(MuhComponent));
const instances = elements.map((element) => element.injector.get(MuhComponent));

which is a bit verbose.

Do you want to create a pull request?

No

undsoft avatar Jan 10 '22 13:01 undsoft

I don't mind getting a PR with your proposed solution.

NetanelBasal avatar Jan 10 '22 20:01 NetanelBasal