简体   繁体   中英

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

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 class="btn btn-secondary" (click)="assignGroup()" [ngClass]="{'assignGrpDisabled': assignToGrpBtnStatus,'assignToGrpBtn':!assignToGrpBtnStatus}" id="assignGrpBtn"><i class="fa fa-plus-square fa-lg"></i> Assign to Group(s)</button> </div> </ng-template> </ng-container>

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM