Unit Karma Test for Typescript/Angular Method

Asked

Viewed 270 times

0

I’m having trouble testing a method of select, that’s the method:

select(task): any {
    (document.getElementById(task) as HTMLInputElement).select();
};

It is called by html, in this part here:

<button id="button-edit" mat-icon-button aria-label="Alterar" *ngIf="!row.canEdit" (click)="select(row.name)" (click)="checkEdit(row)">
          <mat-icon>edit</mat-icon>
        </button>

My test is like this for now:

it('should select a task', () => {
    const getElementById = spyOn(document, 'getElementById');
    component.select(task[0].name);
    expect(getElementById).toHaveBeenCalled();
  });

I get the following Exception:

TypeError: Cannot read property 'select' of null

1 answer

1


it('should select a task', () => {
    const obj ={
    select: function()=>{}
    }
    const getElementById = spyOn(document, 'getElementById').and.returnValue(obj);

   const select = spyOn(obj, 'select');
   component.select(task[0].name);
   expect(getElementById).toHaveBeenCalled();
   expect(select).toHaveBeenCalled();
  });
  • It worked, thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.