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);
}
}
You could create some test components in your
.spec.tsfile that have yourmy-form-inputcomponent in their templates. Have a look at Angular Material Checkbox tests to see an example of this (you could also addformelement to the test components)Once you've created the component via the
TestBed, and have access to the underlyingnativeElementof theDebugElement, you can use the DOMdispatchEvent()function to trigger custom events such asMouseEventorKeyboarEvent- Netanel Basal (one of the most thorough authors of Angular documentation) has a good exampleTo check that your functions have been called, you would use Jasmine
spyOnapplied to the component instance methods