Home > OS >  Unable to access an element inside ng-template while writing unit test using Jasmine
Unable to access an element inside ng-template while writing unit test using Jasmine

Time:01-15

So I am trying to access a button inside the ng-container but even after setting the value of ngIf condition to true manually the elements inside the element are not getting rendered in my tesing environment. So far I have tried

  • adding aync
  • updating value of ngIf cond in before each
  • updating value of ngIf cond inside the it func itself

nothing seems to work and i keep on getting "TypeError: Cannot read properties of null (reading 'nativeElement')"

it('should call assignGroup function', fakeAsync(() => {
  component.Show = true;
  fixture.detectChanges();
  let button = fixture.debugElement.query(By.css('#assignGrpBtn')).nativeElement;
  console.log(button); // getting null for the btn 
}));
<ng-container *ngIf="Show">
  <ng-template pTemplate="caption">
    <div style="float: left;">
      <button  (click)="assignGroup()" [ngClass]="{'assignGrpDisabled': assignToGrpBtnStatus,'assignToGrpBtn':!assignToGrpBtnStatus}" id="assignGrpBtn"><i ></i> Assign to Group(s)</button>
    </div>
  </ng-template>
</ng-container>

CodePudding user response:

I am thinking your TestBed does not know how to render the pTemplate directive.

You have to do something like this (I assume you're using prime-ng):

import {TableModule} from 'primeng/table';

beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [
        YourComponent,
        // If including TableModule in imports does not work, try including
        // the directive for pTemplate.
        // PTemplateDirective
      ],
      imports:[TableModule]
    }).compileComponents();
  }));

Once TableModule is imported and added to the imports array, the test should know how to paint it.

  •  Tags:  
  • Related