'Testing Reactive Forms in Angular with Karma
I am testing a function that has a reference to a form in it (this.form), so when I try to test it I am wondering how I can mock that form so the function has access to it.
Here is the function I am testing:
export function isInvalid(control: string) {
const _control = this.form?.controls[control];
if (!_control) {
console.log('isInvalid - no control', control)
}
const _touched = _control?.touched;
const _invalid = _control?.invalid;
return _touched && _invalid;
}
Here is the test for the isInvalid function. I created a mock Form but the problem is that the reference to the form (this.form) is inside the function so it can't access the mock form. Any ideas of how I can get around this? Thanks.
it('should check isInvalid - return true', () => {
const form: FormGroup = new FormGroup({
name: new FormControl(''),
});
const control = "name";
expect(isInvalid(control)).toEqual(-1);
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|