【问题标题】:Unable to access an element inside ng-template while writing unit test using Jasmine使用 Jasmine 编写单元测试时无法访问 ng-template 中的元素
【发布时间】:2022-01-12 20:30:02
【问题描述】:

所以我试图访问 ng-container 内的按钮,但即使在手动将 ngIf 条件的值设置为 true 之后,元素内的元素也不会在我的测试环境中呈现。到目前为止我已经尝试过

  • 添加异步
  • 在每个之前更新 ngIf cond 的值
  • 在 it func 中更新 ngIf cond 的值

似乎没有任何效果,我不断收到“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>

【问题讨论】:

    标签: angular typescript unit-testing jasmine karma-jasmine


    【解决方案1】:

    我认为您的 TestBed 不知道如何呈现 pTemplate 指令。

    你必须这样做(我假设你正在使用 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();
      }));
    

    一旦TableModule 被导入并添加到imports 数组中,测试应该知道如何绘制它。

    【讨论】:

    • 谢谢你,它解决了我面临的部分问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-11
    相关资源
    最近更新 更多