0

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

1

1 Answer 1

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>?)

Sign up to request clarification or add additional context in comments.

2 Comments

iam getting an function not implemented error and what is testClickSpy means
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.