Angular 2 test ng-content

angular, javascript

Solution

You have to create another dummy test component that contains this testing component, ie. `app-alert`

@Component({
  template: `<app-alert>Hello World</app-alert>`,
})
class TestHostComponent {}

Make TestHostComponent part of your test bed module

beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [AppAlert, TestHostComponent],
    }).compileComponents();
}));

And then instantiate this testing component, check if that contains the ng-content part, ie. "hello world" text

it('should show ng content content', () => {
    const testFixture = TestBed.createComponent(TestHostComponent);

    const de: DebugElement = testFixture.debugElement.query(
      By.css('div')
    );
    const el: Element = de.nativeElement;

    expect(el.textContent).toEqual('Hello World');
});

Problem

I'm wondering if there is a way to test `ng-content` without creating a host element? For example, if I have alert component - ``` @Component({ selector: 'app-alert', template: ` <div> <ng-content></ng-content> </div> `, }) beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [AlertComponent] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(AlertComponent); component = fixture.componentInstance; }); it('should display the ng content', () => { }); ``` How can I set `ng-content` without creating a host element wrapper?

Original source

Related problems