Unit test fail - is not a function

Viewed 37

I have angular component where I have something like this:

import { SomeInterface } from '../interfaces';

.....

export class SomeComponent implement OnInit, SomeInterface {

valueUpdated(value: string) {
    ....
    if(value.length === 6) {
       this.enterValue = value;
       this.submit();
    }
}

submit() {
    (this as SomeInterface).triggerSomething(true);
    .....some other things
}

.

export interface SomeInterface {
    ....
    triggerSometing(value: boolean);
}

.

it('should call valueUpdated', () => {
    component.valueUpdated('123456');
    fixture.detectChanges();

    const submitSpy = spyOn(component, 'submit' as any);
    
    fixture.whenStable().then(() => {
        fixture.detectChanges();
        expect(submitSpy).toHaveBeenCalled();
    });
});

And then in unit test when I go throw this function unit test fail: this.triggerSomething is not a function.

How can I fix it, maybe mock this interface in unit test but I do not know how exactly to do that.

1 Answers

The interface SomeInterface is there as a contract to ensure that whoever implements it, implements it correctly.

This means that if SomeComponent implements it, it should have a triggerSomething method.

When you do:

export class SomeComponent implements OnInit, SomeInterface {

Does the TypeScript compiler complain? It should be.

Also, the main issue is this:

(this as SomeInterface).triggerSomething(true);

We are casting this to SomeInterface and then we call triggerSomething where it does not exist.

To fix it quickly, you can do:

submit() {
    this.triggerSomething(true);
    .....some other things
}

triggerSomething(value: boolean) {
  // do nothing - just make the interface happy
}
Related