I need to be able to mock angular's ng-template
for a unit test. When I try to run it I get this error:
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>
")
Here is my mock verson of ng-template
@Component({
selector: "ng-template",
template: "<div><ng-content></ng-content></div>",
})
export class NgTemplateStub {}
Here is the actual template I am trying to mock
<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>
Here is the TestModule
fixture = TestBed.configureTestingModule({
declarations: [
...
FormsGridComponent,
NgTemplateStub,
],
imports: [
...
],
providers: [
...
],
}).createComponent(GridComponent)
Is it possible to mock ng-template
?
You can accomplish this by creating a WrapperComponent
before your test spec:
@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'
}];
}
Then, in your beforeEach you can get a reference to the wrapper and the component under test to use in each test case:
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;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With