1

I am writing Karma tests for my angular application. I use custom form controlls that are created with the ControllValueAccessor.

Is there a way to test the implemented ControllValueAccessor methods (registerOnChange, ...)

@Component({
    selector: 'my-form-input',
    templateUrl: 'input.html',
    providers: [
        {
            provide: NG_VALUE_ACCESSOR,
            useExisting: forwardRef(() => InputComponent),
            multi: true
        }
    ]
})
export class InputComponent extends InputAbstractComponent {
    @Input() showPlaceHolder: Boolean = true;
    value = undefined;

    onChange = (value: string) => {
    };
    onTouched = (touched: boolean) => {
    };

    registerOnChange(fn: any): void {
        this.onChange = fn;
    }

    registerOnTouched(fn: any): void {
        this.onTouched = fn;
    }

    setDisabledState(isDisabled: boolean): void {
    }

    writeValue(value: string): void {
        this.value = value;
    }

    updateValue(value: string): void {
        this.onTouched(true);
        this.onChange(value);
    }
}
Nealv
  • 6,856
  • 8
  • 58
  • 89
  • 1
    Test it as you would do with a component you didn't write: by using your component in a form, and checking it behaves correctly: does it update the model when you enter something in it? Does it display the value set programmatically? Does it become visually disabled when you disable the form control? etc. – JB Nizet Oct 19 '19 at 09:57

1 Answers1

0

You could create some test components in your .spec.ts file that have your my-form-input component in their templates. Have a look at Angular Material Checkbox tests to see an example of this (you could also add form element to the test components)

Once you've created the component via the TestBed, and have access to the underlying nativeElement of the DebugElement, you can use the DOM dispatchEvent() function to trigger custom events such as MouseEvent or KeyboarEvent - Netanel Basal (one of the most thorough authors of Angular documentation) has a good example

To check that your functions have been called, you would use Jasmine spyOn applied to the component instance methods

Drenai
  • 11,315
  • 9
  • 48
  • 82