Home > front end >  how to unit test a variable that generates an id randomly
how to unit test a variable that generates an id randomly

Time:08-12

Good morning people I have the following code that I am trying to carry out a unit test

<div *ngIf="primaryLabel" >
    <div  *ngIf="!secondaryLabel">
      <a  id="primaryAct[{{ id }}]" (click)="runPrimaryAction($event)">{{ primaryLabel }}</a>
    </div>
  it('should have been clicked in primary action', () => {
      spyOn(component.primaryAction, 'emit');

      fixture.detectChanges();

      const link = nativeElement.querySelector('?????'); //code here

      spyOn(eventClick, 'stopPropagation');

      link.dispatchEvent(eventClick);

      expect(component.primaryAction.emit).toHaveBeenCalledWith();
      expect(eventClick.stopPropagation).toHaveBeenCalled();
    });

CodePudding user response:

You could add a custom id within your HTML element and test it like this:

<div  *ngIf="!secondaryLabel">
  <a 
    
   [attr.my-id]="'someUniqueId'"
   id="primaryAct[{{ id }}]" 
   (click)="runPrimaryAction($event)">{{ primaryLabel }}
  </a>
</div>
//...
const link = fixture.debugElement.nativeElement.querySelector('[my-id="someUniqueId"]');
//...
  • Related