简体   繁体   中英

[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)

Use Object.assign() like below:

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

You can use ng-mocks to mock SelectOption .

beforeEach(() => {
  return TestBed.configureTestingModule({
    declarations: [
      MyComponent,
      MockComponent(SelectOption), // or MockDirective
    ],
  }).compileComponents();
});

it('testing', () => {
  const fixture = MockRender(`
    <my-component>
      <select-option value="1"></select-option>
      <select-option value="2"></select-option>
    </my-component>
  `);

  const component = ngMocks.findInstance(MyComponent);

  expect(component.selectOptions.size).toEqual(2);
  // and other assertions.
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM