How to test ControllValueAccessor in Angular2

754 Views Asked by At

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);
    }
}
1

There are 1 best solutions below

0
Drenai On

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