title: Why doesn't my Angular test like my custom form validation function?
body: <p>I have an angular component - "FooComponent" - that I'm trying to test using Karma/Jasmine.</p>
  
  <p>Here is some relevant code in the foo.component.spec.ts file:</p>
  
  <pre><code>describe('FooComponent', () =&gt; {
      let component: FooComponent
      let fixture: ComponentFixture&lt;FooComponent&gt;
      let componentElement: DebugElement
      let bar: FormControl
  
  ...
  
  beforeEach(() =&gt; {
      fixture = TestBed.createComponent(FooComponent)
      component = fixture.componentInstance
      fixture.detectChanges()
      component.ngOnInit()
      componentElement = fixture.debugElement
      bar = component.bar
    })
  
  it('should create the FooComponent', () =&gt; {
      expect(component).toBeTruthy()
  })
  </code></pre>
  
  <p>I'm getting the following error when running <code>ng test</code> :</p>
  
  <pre><code>Chrome 63.0.3239 (Windows 10 0.0.0) FooComponent should create the 
  FooComponent FAILED
  
      TypeError: Cannot read property 'validate' of undefined
          at normalizeValidator .../node_modules/@angular/forms/esm5/forms.js:1059:23)
          at Array.map (&lt;anonymous&gt;)
          at composeValidators .../node_modules/@angular/forms/esm5/forms.js:2422:1)
          at coerceToValidator .../node_modules/@angular/forms/esm5/forms.js:2826:1)
          at new FormControl .../node_modules/@angular/forms/esm5/forms.js:3881:1)
          at FooComponent.webpackJsonp.../../../../../src/app/foo/foo.component.ts.FooComponent.createFormControls ....../src/app/foo/foo.component.ts:43:16)
          at FooComponent.webpackJsonp.../../../../../src/app/foo/foo.component.ts.FooComponent.ngOnInit ....../src/app/foo/foo.component.ts:37:10)
          at checkAndUpdateDirectiveInline .../node_modules/@angular/core/esm5/core.js:12400:1)
          at checkAndUpdateNodeInline .../node_modules/@angular/core/esm5/core.js:13927:1)
          at checkAndUpdateNode .../node_modules/@angular/core/esm5/core.js:13870:1)
  </code></pre>
  
  <p>As you can see, lines 37 and 43 of foo.component.ts are offensive:</p>
  
  <pre><code>ngOnInit() {
      //the following is line 37
      this.createFormControls()
      this.createForm()
  }
  
  createFormControls() {
      //the following is line 43
      this.bar = new FormControl('', [Validators.required, this.fooService.validateBar])
  }
  
  createForm() {
      this.fooForm = new FormGroup({
          bar: this.bar
      })
  }
  </code></pre>
  
  <p>So it looks like it does not like something about the custom validation function I wrote in FooService (which I am injecting into FooComponent). Here is that function within foo.service.ts:</p>
  
  <pre><code>validateBar(bar: FormControl) {
      return bar.value.length == 10 ? null: { invalidBar: true }
  }
  </code></pre>
  
  <p>Any ideas?</p>