Home > Net >  Angular Jasmine - expect().toHaveBeenCalled() not working
Angular Jasmine - expect().toHaveBeenCalled() not working

Time:07-09

if anyone can help me debug my unit test code I would appreciate it. Basically I'm attempting to test whether a couple of methods are invoked upon a button's click() event. They run fine on the actual app, but apparently not while testing:

fit('Cancel button should trigger dialog modal', () => {
    spyOn(_myService, 'showDialogModal');
    spyOn(component, 'confirmCancel');

    const cancelButton = fixture.debugElement.nativeElement.querySelector('.cancelButton');
    cancelButton.click();

    fixture.detectChanges();

    expect(component.confirmCancel).toHaveBeenCalled();
    expect(_myService.showDialogModal).toHaveBeenCalledWith(
      header, message
    );
  });

Upon execution, I'm getting:

expect(spy).toHaveBeenCalled()

    Expected number of calls: >= 1
    Received number of calls:    0

This is for the method component.confirmCancel(), whereas the second one is called from within that function.

CodePudding user response:

Two ideas for debugging:

  • To see if sth is wrong about your spy setup: check if the method you expect to be called is actually called when you execute the test. E.g. put a console.log in that method, or put a breakpoint and run the test in debug mode.
  • Check if the element that you query via '.cancelButton' is really the element that has the click listener.

It could be helpful if you also post the relevant html and ts code of the component.

  • Related