如何测试Angular2中的transclusion(ng-content)?

时间:2017-02-24 13:48:52

标签: angular unit-testing testing angular2-testing

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

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

    });

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

1 个答案:

答案 0 :(得分:5)

我认为你可以在不使用包装器的情况下完成它,因为有办法通过调用来获取主机元素:

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