3

version: Angular 4.

I am injecting a parent component into child component to access parent method through child component.

In parent-component I had to use ChangeDetectorRef because it has a property which will update runtime.

Now code is working fine but child-component spec is throwing error for "ChangeDetectorRef" which is injected in parent component.

Error: No provider for ChangeDetectorRef!

Parent Component

import { Component, AfterViewChecked, ChangeDetectorRef, ChangeDetectionStrategy } from '@angular/core';

@Component({
  selector: 'parent-component',
  templateUrl: './parent.component.html',
  styleUrls: ['./parent.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ParentComponent implements AfterViewChecked {

  stageWidth: number;

  constructor(private ref: ChangeDetectorRef) {
    this.ref = ref;
  }

  //call this function as many times as number of child components within parent-component.
  parentMethod(childInterface: ChildInterface) {
    this.childInterfaces.push(childInterface);
  }

  ngAfterViewChecked() {
    this.elementWidth = this.updateElementWidthRuntime();
    this.ref.detectChanges();
  }
}

Child Component

import { Component, AfterViewInit } from '@angular/core';
import { ParentComponent } from '../carousel.component';

@Component({
  selector: 'child-component',
  templateUrl: './carousel-slide.component.html',
  styleUrls: ['./carousel-slide.component.scss'],
})
export class ChildComponent implements AfterViewInit {

  constructor(private parentComponent: ParentComponent) {
  }

  ngAfterViewInit() {
    this.parentComponent.parentMethod(this);
  }
}

app.html

<parent-component>
    <child-component>
      <div class="box">Content of any height and width</div>
    </child-component>
    <child-component>
      <div class="box">Content of any height and width</div>
    </child-component>
    <child-component>
      <div class="box">Content of any height and width</div>
    </child-component>
</parent-component>

Unit test for Child Component

import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { ParentComponent } from '../parent.component';
import { ChildComponent } from './child.component';

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

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

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

  it('should create \'ChildComponent\'', () => {
    expect(component).toBeTruthy();
  });
});

When I am trying to add ChangeDetectorRef in providers in child spec, I am getting following error.

Failed: Encountered undefined provider! Usually this means you have a circular dependencies (might be caused by using 'barrel' index.ts files.)

After googling and trying many things I am unable to find solution. Any help appreciated.

  • Are you making circular dependencies or 'barrel' index.ts? – Tatsuyuki Ishi Mar 30 '17 at 1:10
  • @Tatsuyuki Ishi No I am not using circular dependencies. Just above code and some calculations. – TechFreak Mar 30 '17 at 1:43
2

You are using a component as a provider, which is probably not your intention. Change your test module to declare both your parent and child components.

TestBed.configureTestingModule({
  declarations: [ChildComponent, ParentComponent],
  providers: []  
})
|improve this answer|||||
  • If I do like this then I am getting Error: No provider for ParentComponent! – TechFreak Mar 30 '17 at 1:44
  • why does Angular think ParentComponent needs a provider? did you decorate it (ParentComponent) with a @Component decorator? – snorkpete Mar 30 '17 at 3:04
  • Because I am injecting parent component into child component. If you see my child component you can see it in constructor. Reason I am doing this is I have to call parent method from child component. – TechFreak Mar 30 '17 at 3:08
  • Reaching here, but try both declaring and providing ParentComponent – snorkpete Mar 30 '17 at 3:11
  • 1
    In this case you're not unit testing - you're doing a limited integration test between the two components, so you probably need to create a test harness component that has the proper hierarchy. That should allow the dependency injection to work. – snorkpete Mar 30 '17 at 3:17
1

I am able to get rid of this error by making "ChangeDetectorRef" as @Optional dependency in my Parent Component.

constructor(@Optional() private ref: ChangeDetectorRef) {
    this.ref = ref;
}

This way my child component's configureTestingModule will ignore ParentComponent provider.

|improve this answer|||||
  • 1
    I'd been on this for a day, and you helped. Thanks. It makes sense to make it optional in a unit test or storybook scenario. – mykeels Nov 12 '19 at 9:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.