如何在 Angular2 中测试包含(ng-content)?

How to test transclusion (ng-content) in Angular2?

我有一个组件要测试如下:

import {Component, OnInit, Input} from "@angular/core";

@Component({
    selector: 'column',
    template: '<ng-content></ng-content>',
    host: {
        '[class]': '"col col-" + width'
    }
})
export class ColumnComponent implements OnInit {

    @Input() public width: number;

    ngOnInit() {
        if (!this.width || this.width > 12 || this.width < 1) {
            this.width = 12;
        }
    }

}

我无法找到一种优雅的方法来测试 <ng-content>。检查文档但找不到好的方法。

我认为拥有一个测试包装器组件会有所帮助。但是 comp 不是使用的 TestContainerComponent 所以测试失败

  @Component({
        selector: 'test-container',
        template: `<column width="12">Hello</column>`
    })
    export class TestContainerComponent {
    }

    fdescribe(`Column`, () => {
        let comp: ColumnComponent;
        let fixture: ComponentFixture<ColumnComponent>;

        let testContainerComp: TestContainerComponent;
        let testContainerFixture: ComponentFixture<TestContainerComponent>;
        let testContainerDe: DebugElement;
        let testContainerEl: HTMLElement;

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

        beforeEach(() => {
            fixture = TestBed.createComponent(ColumnComponent);
            testContainerFixture = TestBed.createComponent(TestContainerComponent);
            comp = fixture.componentInstance;

            testContainerComp = testContainerFixture.componentInstance;
            testContainerDe = testContainerFixture.debugElement.query(By.css('column'));
            testContainerEl = testContainerDe.nativeElement.;

        });


        it(`Should have a width class as 'col-...' if width attribute set`, () => {
            comp.width = 6;
            testContainerFixture.detectChanges();
         expect(testContainerEl.classList.contains(`col-${comp.width}`)).toBeTruthy();
        });

    });

我想我需要一种从 TestContainerComponent 获取 ColumnComponent 组件的方法。

我认为你可以在不使用包装器的情况下做到这一点,因为可以通过调用获取宿主元素:

fixture.elementRef.nativeElement;

所以这是可能的测试:

fdescribe(`Column`, () => {
  let comp: ColumnComponent;
  let fixture: ComponentFixture<ColumnComponent>;

  let testContainerDe: DebugElement;
  let testContainerEl: HTMLElement;

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

  beforeEach(() => {
    fixture = TestBed.createComponent(ColumnComponent);
    comp = fixture.componentInstance;
    testContainerEl = fixture.elementRef.nativeElement;
  });

  it(`Should have a width class as 'col-...' if width attribute set`, () => {
    comp.width = 6;
    fixture.detectChanges();
    expect(testContainerEl.classList.contains(`col-${comp.width}`)).toBeTruthy();
  });
});

Plunker Example