Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mock the <ng-template> for unit test - Angular 2

Tags:

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?

like image 751
ed-tester Avatar asked Jun 21 '17 23:06

ed-tester


1 Answers

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;
});
like image 149
aaron-bond Avatar answered Oct 13 '22 00:10

aaron-bond