Search code examples
angularunit-testingmockingjasmineangular-content-projection

[Angular Unit Test]: How can I mock QueryList in a Unit Test (No integration test)


In a Content Projection scenario I have the following scenario:

// my-component.ts
 @ContentChildren(SelectOption) selectOptions: QueryList<SelectOption>;

...
ngAfterContentInit() {
    this.selectOptions.forEach((selectOption, i) => {
       selectOption.index = i;
    });
}

Assuming the template has the following structure:

<ng-content select="select-option"></ng-content>

I have tried to mock the test in the following way but I can't find an "add" method that allows me to add the child components.

// my-component.spec.ts
component.selectOptions = {} as QueryList<SelectOption>;

But I don't know how I can add the projected components in a unit test scenario (not an integration test)


Solution

  • Use Object.assign() like below:

    Object.assign(new QueryList(), {_results: [selectOptionMock1, selectOptionMock2, selectOptionMock3]}) as QueryList<SelectOption>;