无法使用 ngif 读取 null 的 属性 'nativeElement'

Cannot read property 'nativeElement' of null with ngif

我正在做一些单元测试。

所以我有这个功能:

selectCluster(event: MouseEvent, feature: any) {
    event.stopPropagation(); 
    this.selectedCluster = {geometry: feature.geometry, properties: feature.properties};
  }

和模板:


 <mgl-popup *ngIf="selectedCluster" [feature]="selectedCluster">
      
    </mgl-popup>

我有这样的测试:

  fit('Should set selectedCluster when clicked', async(() => {    

    spyOn(component, 'selectCluster').and.callThrough();
    fixture.detectChanges();
    fixture.debugElement.query(By.css('.marker-cluster')).nativeElement.click();
    tick();

    fixture.whenStable().then(() => {
      expect(component.selectCluster).toHaveBeenCalled();
    });
  }));

但我仍然得到这个错误:

Cannot read property 'nativeElement' of null

那么我必须改变什么?

谢谢

这也用到了函数:

 <ng-template mglClusterPoint let-feature>
        <div class="marker-cluster" (click)="selectCluster($event, feature)">
          <fa-icon [icon]="faVideo" [styles]="{'stroke': 'black', 'color': 'black'}" size="lg" class="pr-2"></fa-icon>
          <fa-icon [icon]="faWifi" [styles]="{'stroke': 'black', 'color': 'black'}" size="lg" class="pr-2"></fa-icon>
        </div>
      </ng-template>
当您尝试单击

.marker-cluster 时,它不在页面上,我没有看到您的完整 html,但我认为它与 *ngIf="selectedCluster" 相关。

 fit('Should set selectedCluster when clicked', async(() => {    
    // spy on and calling through doesn't actually call the function
    // it makes it so we can determine if the function was called
    // and everytime the function was called, call the actual function
    // and not a null function
    spyOn(component, 'selectCluster').and.callThrough();
    // calling the function will should make selectedCluster true
    component.selectCluster({ stopPropagation: () => null } as MouseEvent, {}); // send your own inputs
    fixture.detectChanges();
    fixture.debugElement.query(By.css('.marker-cluster')).nativeElement.click();

    fixture.whenStable().then(() => {
      expect(component.selectCluster).toHaveBeenCalled();
    });
  }));