【发布时间】:2017-07-15 09:11:32
【问题描述】:
我有一个组件要测试如下:
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 组件的方法。
【问题讨论】:
-
使用
ViewChild持有对ColumnComponent的引用怎么样?
标签: angular unit-testing testing angular2-testing