-1

I am doing some unit tests.

So I have this function:

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

and tempplate:


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

and I have the test like this:

  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();
    });
  }));

But I still get this error:

Cannot read property 'nativeElement' of null

So what I have to change?

Thank you

This also use the function:

 <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>
CodeIsNice
  • 31
  • 5

1 Answers1

1

.marker-cluster is not on the page when you attempt to click it, I don't see your full html but I will assume it is related to *ngIf="selectedCluster" being true.

 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();
    });
  }));
AliF50
  • 16,947
  • 1
  • 21
  • 37