我需要能够模拟角度ng-template
进行单元测试。当我尝试运行它时,我收到此错误:
Components on an embedded template: NgTemplateStub ("
<grid-column>
[ERROR ->]<ng-template gridCellTemplate dataItem>
<custom-column-template [data]="dataItem"></custom-column-template>
</ng-template>
<grid-column>
")
这是我ng-template
@Component({
selector: "ng-template",
template: "<div><ng-content></ng-content></div>",
})
export class NgTemplateStub {}
这是我试图模拟的实际模板
<grid [data]="form$ | async" [pageSize]="pageSize">
<grid-column width="50">
<ng-template gridCellTemplate dataItem>
<custom-column [dataItem]="dataItem"></custom-column>
</ng-template>
</grid-column>
<!-- other columns -->
</grid>
这是TestModule
fixture = TestBed.configureTestingModule({
declarations: [
...
FormsGridComponent,
NgTemplateStub,
],
imports: [
...
],
providers: [
...
],
}).createComponent(GridComponent)
是否可以模拟ng-template
?
答案 0 :(得分:2)
您可以通过在测试规范之前创建WrapperComponent
来实现此目的:
@Component({
template: `
<my-custom-component [(dataItems)]='dataBinding'>
<ng-template #my-template let-item>
<h1>{{item.Text}}</h1>
</ng-template>
</my-custom-component>`
})
class WrapperComponent {
@ViewChild(MyCustomComponent) myCustomComponent: MyCustomComponent;
public dataBinding = [{
Text: 'Hello'
},{
Text: 'World'
}];
}
然后,在您的beforeEach中,您可以获得对包装器和被测组件的引用,以便在每个测试用例中使用:
beforeEach(() => {
...
let fixture = TestBed.createComponent(WrapperComponent);
let wrapperComponent = fixture.componentInstance;
// get a reference to the actual component we want
let component = fixture.componentInstance.myCustomComponent;
let itemElement = fixture.debugElement.nativeElement;
});