简体   繁体   中英

How to execute method on child component in an Angular unit test

I am running an Angular 5 application with the default test setup (Jasmine + Karma).

Let's say there is a component named Parent, having a method executing a method on child component.

parent.component.ts

@Component({
  selector: 'parent',
...
export class ParentComponent implements {
  @ViewChild(ChildComponent) childComponent: ChildComponent;

  executeChildComponentMethod() {
    this.childComponent.methodToTest();
  }
}

parent.component.spec.ts

import { ParentComponent } from './parent.component'

describe('ParentComponent' () => {
  let component: ParentComponent;
  let fixture: ComponentFixture<ParentComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ParentComponent],
        schemas: [NO_ERRORS_SCHEMA]
      })
      .compileComponents();
    }));

  beforeEach(() => {
    fixture = TestBed.createComponent(ParentComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should trigger executeChildComponentMethod', () => {
    component.executeChildComponentMethod()
  });
});

This results in the tests throwing error saying, unable to execute methodToTest of undefined.. which means the child component is not instantiated.

Have tried approaches like instantiating a child component inside the it block, injecting the child component to the it block and instantiating child component from another fixture (for child component) in the test block but to no avail.

How can I get the test working?

Add ChildComponent to declarations array, so that it is part of your unit test, which means it will be rendered in the view.

 beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ParentComponent, ChildComponent],
        schemas: [NO_ERRORS_SCHEMA]
      })
      .compileComponents();
  }));

Note : You may have to add providers of ChildComponent as well.

EDIT :

Alternate approach

First of all, as a part of unit testing you should not be testing the behavior of child component inside parent component. If you want to check only if child component method is called or not, then you may mock the child component and define a method that you are testing inside it. This way, you need not depend on the child providers during testing.

See here for mocking child components.

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