import { FormControl } from '@angular/forms'; import { phoneValidator } from './phone-validator'; describe('Phone validator', () => { let control: FormControl; const hint: string = 'e.g., 555/555-5555, (555) 555-5555'; beforeEach(() => { control = new FormControl(); control.setValidators(phoneValidator); }); it('should not validate when control value is empty', () => { control.updateValueAndValidity(); expect(control.hasError('invalidFormat')).toBe(false); }); it('should return undefined on phone number of format xxxxxxxxxx', () => { control.setValue('5555555555'); control.updateValueAndValidity(); expect(control.hasError('invalidFormat')).toBe(false); }); it('should return undefined on phone number of format xxx-xxx-xxxx', () => { control.setValue('555-555-5555'); control.updateValueAndValidity(); expect(control.hasError('invalidFormat')).toBe(false); }); it('should return undefined on phone number of format (xxx) xxx-xxxx', () => { control.setValue('(555) 555-5555'); control.updateValueAndValidity(); expect(control.hasError('invalidFormat')).toBe(false); }); it('should return undefined on phone number of format (xxx)-xxx-xxxx', () => { control.setValue('(555)-555-5555'); control.updateValueAndValidity(); expect(control.hasError('invalidFormat')).toBe(false); }); it('should return undefined on phone number of format xxx xxx xxxx', () => { control.setValue('555 555 5555'); control.updateValueAndValidity(); expect(control.hasError('invalidFormat')).toBe(false); }); it('should return undefined on phone number of format xxx/xxx-xxxx', () => { control.setValue('555/555-5555'); control.updateValueAndValidity(); expect(control.hasError('invalidFormat')).toBe(false); }); it('should return a validation error on other values', () => { const values: string[] = [ ' ', '1', 'xxxxxxxxxx', 'xxx-xxx-xxxx', '(xxx) xxx-xxxx', '(xxx)-xxx-xxxx', 'xxx xxx xxxx', ]; for (let value of values) { control.setValue(value); control.updateValueAndValidity(); expect(control.hasError('invalidFormat')).toBe(true); expect(control.errors.invalidFormat).toEqual({hint}); } }); });