Angular 2 test ng-content

Viewed 9177

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?

2 Answers

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');
});

I was wondering about the same thing as you:

After taking a look at: Angular projection testing

I ended up with something like this:

@Component({
template: '<app-alert><span>testing</span></app-alert>'
})
export class ContentProjectionTesterComponent {
}

describe('Content projection', () => {

let component: ContentProjectionTesterComponent;
let fixture: ComponentFixture<ContentProjectionTesterComponent>;

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

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

it('Content projection works', async () => {
let text = 'testing';
fixture = TestBed.createComponent(ContentProjectionTesterComponent);
component = fixture.componentInstance;
let innerHtml = fixture.debugElement.query(By.css('span')).nativeElement.innerHTML;
expect(innerHtml).toContain(text);
});
});
Related