4

I have a need to test that my @ContentChildren are being populated correctly using Jasmine, but I can't get my test to work. As it happens, there is a very similar question and answer here, but my code fails on the line indicated below.

Here is the code:

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

import { RadioButtonGroupComponent } from './radio-button-group.component';

@Component({
  selector: 'sas-radio-button-test',
  template: `<sas-radio-button-group>
  <sas-radio-button text="Radio button 0" value="0" checked="true"></sas-radio-button>
  <sas-radio-button text="Radio button 1" value="1"></sas-radio-button>
  <sas-radio-button text="Radio button 2" value="2"></sas-radio-button>
</sas-radio-button-group>`,
})
class TestWrapperComponent {
}

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

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

  beforeEach(() => {
    fixture = TestBed.createComponent(TestWrapperComponent);
    component = fixture.debugElement.children[0].componentInstance;
    fixture.detectChanges();
  });

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

  it('should have the correct number of children', () => {
    expect(component.radioButtons.length).toBe(3); // <!--- this is zero when it should be 3
  });
});

My component fragment looks like this:

export class RadioButtonGroupComponent implements AfterContentInit {
    @ContentChildren(RadioButtonComponent) radioButtons: QueryList<RadioButtonComponent>;
    //...
}

Can anyone help?

serlingpa
  • 12,024
  • 24
  • 80
  • 130

1 Answers1

1

You can put fixture.detectChanges(); in the test case (inside it) and remove fixture.detectChanges() from beforeEach

it('should have the correct number of children', () => {
    fixture.detectChanges()
    expect(component.radioButtons.length).toBe(3); 
  });

beforeEach is the init step. Changes are applied in the test case level.

Terence
  • 652
  • 11
  • 34