ed-*_*ter 5 templates unit-testing jasmine angular
我需要能够模拟 angularng-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>
")
Run Code Online (Sandbox Code Playgroud)
这是我的模拟版本 ng-template
@Component({
selector: "ng-template",
template: "<div><ng-content></ng-content></div>",
})
export class NgTemplateStub {}
Run Code Online (Sandbox Code Playgroud)
这是我试图模拟的实际模板
<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>
Run Code Online (Sandbox Code Playgroud)
这是测试模块
fixture = TestBed.configureTestingModule({
declarations: [
...
FormsGridComponent,
NgTemplateStub,
],
imports: [
...
],
providers: [
...
],
}).createComponent(GridComponent)
Run Code Online (Sandbox Code Playgroud)
可以模拟ng-template
吗?
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'
}];
}
Run Code Online (Sandbox Code Playgroud)
然后,在 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;
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
7843 次 |
最近记录: |