简体   繁体   中英

How to Access child component property in spec file as QueryList in Angular using @viewChildren

I have the below code in the parent.component.ts file, where I'm accessing the child grid as QueryList using @ViewChildren.

@ViewChildren(ChildComponent) childComponent: QueryList<any>;

I have this below function in the component where I accessed the childComponent property like this.

checkProperty() { 
 let isNewRow = this.childComponent[_results].some(
   item => item.newRowCreated === true
 )
 if(isNewRow) { 
  this.newRowEnabled = true;
 }
}

While writing jasmine test for checkProperty() method the mock data which I created for this is throwing error and I'm unable to test this method. Please find the test case code.

it('test checkProperty() method', () => {
  component.childComponent = {
    changes: {},
    first: {},
    last: {},
    length: 1,
    dirty: false,
    _results: [{newRowCreated: true}]
  }
  fixture.detectChanges();
  component.checkProperty();
  expect(component.newRowEnabled).toBe(true);
});
   

This code is throwing error in place where the childComponent is mocked in the spec file. Im getting the below error.

Type 'changes: {},first: {},last: {},length: 1,dirty: false,_results: [{newRowCreated: true}' is missing the following properties form type QueryList<any>: map,filter, find, reduce and 7 more.

Is this the right way to mock the childComponent as QueryList? Please help to fix this.

To mock things you could use ng-mocks .

It supports mock child components, @ViewChildren : https://ng-mocks.sudo.eu/guides/view-child , etc.

So you may try something like that:

beforeEach(() => TestBed.configureTestingModule({
  declarations: [
    ParentComponent,
    // Mocking the child component
    MockComponent(ChildComponent),
  ],
}));

it('test checkProperty() method', () => {
  // changing properties of the child component
  ngMocks.findInstance(ChildComponent).newRowCreated = true;

  // triggers and assertions
  fixture.detectChanges();
  component.checkProperty();
  expect(component.newRowEnabled).toBe(true);
});

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