Spying on super class methods in Angular Unit Test with Jasmine/Karma

Discussão em 'Angular' iniciado por Jarvis, Janeiro 3, 2025.

  1. Jarvis

    Jarvis Guest

    I am writing unit tests for an Angular component class that extends DualListComponent. The subclass, CustomDualListComponent, has a method onClickElement that calls a couple of super class methods selectItem and shiftClick:

    onClickElement(disabled, item, confirmed, event, idx) {
    if (disabled || this.isLocked(item)) {
    return;
    }
    super.selectItem(confirmed.pick, item);
    super.shiftClick(event, idx, confirmed, item);
    }


    I want to test this method by verifying that selectItem and shiftClick methods get called with correct parameters. In my Jasmine test file, I tried to spy on these methods like:

    const selectItemSpy = spyOn(CustomDualListComponent.prototype, 'selectItem');
    const shiftClickSpy = spyOn(CustomDualListComponent.prototype, 'shiftClick');

    // Call onClickElement method

    expect(selectItemSpy).toHaveBeenCalled();
    expect(shiftClickSpy).toHaveBeenCalled();


    However, my tests fail with "Expected spy selectItem to have been called. But it was never called." error. I suspect this is due to super keyword which directly accesses methods in the superclass and bypasses any in the subclass.

    I understand that a typical advice would be to refactor onClickElement to use this instead of super but due to certain constraints, I am unable to modify the actual component's code. Is there a way to successfully spy on these super class methods called with super keyword in the method of the subclass?

    Thank you in advance for your help.

    Continue reading...

Compartilhe esta Página