简体   繁体   English

使用 Jasmine 编写单元测试时无法访问 ng-template 中的元素

[英]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.所以我试图访问 ng-container 内的按钮,但即使在手动将 ngIf 条件的值设置为 true 之后,元素内的元素也不会在我的测试环境中呈现。 So far I have tried到目前为止我已经尝试过

  • adding aync添加异步
  • updating value of ngIf cond in before each在每个之前更新 ngIf cond in 的值
  • updating value of ngIf cond inside the it func itself在 it func 本身中更新 ngIf cond 的值

nothing seems to work and i keep on getting "TypeError: Cannot read properties of null (reading 'nativeElement')"似乎没有任何效果,我不断收到“TypeError:无法读取 null 的属性(读取'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.我认为您的TestBed不知道如何呈现pTemplate指令。

You have to do something like this (I assume you're using prime-ng):你必须做这样的事情(我假设你正在使用 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.一旦TableModule被导入并添加到imports数组中,测试应该知道如何绘制它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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