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

我正在做一些单元测试。


所以我有这个功能:


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>


www说
浏览 161回答 1
1回答

一只斗牛犬

.marker-cluster当您尝试单击它时,它不在页面上,我没有看到您的完整 html,但我会假设它与*ngIf="selectedCluster"真实相关。&nbsp;fit('Should set selectedCluster when clicked', async(() => {&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; // spy on and calling through doesn't actually call the function&nbsp; &nbsp; // it makes it so we can determine if the function was called&nbsp; &nbsp; // and everytime the function was called, call the actual function&nbsp; &nbsp; // and not a null function&nbsp; &nbsp; spyOn(component, 'selectCluster').and.callThrough();&nbsp; &nbsp; // calling the function will should make selectedCluster true&nbsp; &nbsp; component.selectCluster({ stopPropagation: () => null } as MouseEvent, {}); // send your own inputs&nbsp; &nbsp; fixture.detectChanges();&nbsp; &nbsp; fixture.debugElement.query(By.css('.marker-cluster')).nativeElement.click();&nbsp; &nbsp; fixture.whenStable().then(() => {&nbsp; &nbsp; &nbsp; expect(component.selectCluster).toHaveBeenCalled();&nbsp; &nbsp; });&nbsp; }));
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript