Search code examples
angularunit-testingkarma-jasmine

Angular unit testing - test ng-content


I have an expansion panel component that wraps content dynamically:

<div class="expansion-panel">
  <ng-content></ng-content>
</div>

If you'd use this component it would be like this

<expansion-panel>
  // any content
</expansion-panel>

I want to write a unit test that checks whether the content renders correctly, but I can't find any way to insert some content (other than fixture.nativeElement.innerHTML = 'content', but that's not the right way). How do I do this?


Solution

  • Use a test host component for your test:

    @Component({
      template: `
        <expansion-panel>
          content
        </expansion-panel>
      `,
    })
    class TestComponent {
      @ViewChild(ExpansionPanelComponent, { static: false }) child: ExpansionPanelComponent;
    }
    
    describe('ExpansionPanelComponent', () => {
      let component: TestComponent;
      let fixture: ComponentFixture<TestComponent>;
    
      beforeEach(async () => {
        await TestBed.configureTestingModule({
          declarations: [TestComponent, ExpansionPanelComponent],
        }).compileComponents();
    
        fixture = TestBed.createComponent(TestComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
      });
    
      it('should render content', () => {
        expect(component.child.innerText).ToEqual('content');
      });
    });
    
    

    As above, you can use component.child to access the <expansion-panel> instance