-1

I write a code for unit testing but it isn't worked. I wanna know how to use it and I am new to unit testing

COMPONENT.HTML

<button class="set-button" (click)="clickFunction()"> SAVE</button>

COMPONENT.TS

clickFunction(){
console.log('WORKED');
}

COMPONENT.SPECS.TS

    it('function on button click ', () => {
    spyOn(component, 'clickFunction');
    let btn = fixture.debugElement.nativeElement.querySelector('set-button');
    fixture.detectChanges();
    fixture.whenStable().Then(() =>{
    expect(component.clickFunction).toHaveBeenCalled();
    })
  });

I want to know what have i done wrong here.Thanks in advance

larabrookk
  • 103
  • 1
  • 7
  • Does this help? [stack overflow answer](https://stackoverflow.com/questions/40093013/unit-testing-click-event-in-angular) – Naren Murali Jul 06 '22 at 02:42

1 Answers1

1

the issue is that you never actually perform any click on your button:

  it('should click button', () => {
    const clickFunctionSpy = spyOn(component, 'clickFunction');
    const btn = fixture.debugElement.nativeElement.querySelector(
      'set-button'
    ) as HTMLButtonElement;
    btn.click();
    expect(testClickSpy).toHaveBeenCalled();
  });

If the test still fail, it might be that your querySelector is wrong (do you have an element with the tag <set-button>?)

Nam
  • 554
  • 4
  • 11
  • iam getting an `function not implemented` error and what is **testClickSpy** means – larabrookk Jul 06 '22 at 04:36
  • So in short, you create a `spy` whenever you want to test whether a `function` has been called or not. I would highly recommend that you take a look at some tutorial on Angular Testing (there's a really good Udemy course on that too). Unfortunately it is not simple and without understanding the basic, you can't really proceed any further. – Nam Jul 06 '22 at 20:20