I'm currently facing an issue with testing an angular component called "FooComponent" using Karma/Jasmine.
Snippet of code from foo.component.spec.ts file:
describe('FooComponent', () => {
let component: FooComponent
let fixture: ComponentFixture<FooComponent>
let componentElement: DebugElement
let bar: FormControl
...
beforeEach(() => {
fixture = TestBed.createComponent(FooComponent)
component = fixture.componentInstance
fixture.detectChanges()
component.ngOnInit()
componentElement = fixture.debugElement
bar = component.bar
})
it('should create the FooComponent', () => {
expect(component).toBeTruthy()
})
Encountering this error while running ng test
:
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 (<anonymous>)
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)
The issue seems to be related to lines 37 and 43 in foo.component.ts:
ngOnInit() {
//this is line 37
this.createFormControls()
this.createForm()
}
createFormControls() {
//this is line 43
this.bar = new FormControl('', [Validators.required, this.fooService.validateBar])
}
createForm() {
this.fooForm = new FormGroup({
bar: this.bar
})
}
It appears that there might be a problem with the custom validation function implemented in FooService (which is injected into FooComponent). Below is the validation function defined in foo.service.ts:
validateBar(bar: FormControl) {
return bar.value.length == 10 ? null : { invalidBar: true }
}
Any suggestions on how to resolve this?