【发布时间】:2018-07-11 07:06:36
【问题描述】:
我有一个角度组件 - “FooComponent” - 我正在尝试使用 Karma/Jasmine 进行测试。
这里是 foo.component.spec.ts 文件中的一些相关代码:
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()
})
运行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)
如你所见,foo.component.ts 的第 37 和 43 行令人反感:
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
})
}
所以看起来它不喜欢我在 FooService 中编写的自定义验证函数(我将其注入 FooComponent)。这是 foo.service.ts 中的函数:
validateBar(bar: FormControl) {
return bar.value.length == 10 ? null: { invalidBar: true }
}
有什么想法吗?
【问题讨论】:
标签: javascript angular typescript jasmine karma-runner