我有一个简单的离子形式:
<ion-header>
<ion-navbar>
<ion-title>Foo</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<form [formGroup]="fooForm">
<ion-item>
<ion-label floating>Name</ion-label>
<ion-input formControlName="name" type="text"></ion-input>
</ion-item>
</form>
<button ion-button full color="primary" (click)="save()">Save</button>
</ion-content>
和页面组件:
import { Component } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
@Component({
selector: 'fo-page-foo',
templateUrl: './foo.html'
})
export class FooPage {
fooForm: FormGroup;
constructor(public formBuilder: FormBuilder) {
}
ngOnInit() {
this.fooForm = this.formBuilder.group({
name: ['']
});
}
public save() {
console.log(this.fooForm.value);
}
}
和测试:
import { FooPage } from './foo';
import { TestBed, ComponentFixture } from '@angular/core/testing';
import { CUSTOM_ELEMENTS_SCHEMA, DebugElement } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from "@angular/forms";
import { Form } from 'ionic-angular';
describe('Foo Page:', () => {
let comp: FooPage;
let fixture: ComponentFixture<FooPage>;
let de: DebugElement;
beforeEach(() => {
TestBed.configureTestingModule({
schemas: [CUSTOM_ELEMENTS_SCHEMA],
declarations: [FooPage],
providers: [Form],
imports: [FormsModule, ReactiveFormsModule],
});
fixture = TestBed.createComponent(FooPage);
fixture.detectChanges();
comp = fixture.componentInstance;
de = fixture.debugElement;
comp.ngOnInit();
});
describe('.constructor()', () => {
it('Should be defined', () => {
expect(comp).toBeDefined();
});
});
});
项目和测试结构基于https://github.com/marcoturi/ionic-boilerplate。由于错误:No value accessor for form control
,该测试失败。
我正在尝试各种方法,但似乎离子细节和最近的Angular 4的组合使其需要添加一些额外的配置,并且由于角度的变化,现有的某些解决方案不再有效。
我在两天前遇到了这个问题,这要归功于将其隔离到发布,因此能够在稍微相似的问题上找到解决方案基础
重点是将IonicModule
添加到imports
中,但这触发了其他离子导入的束:
import {
App, Platform, Config, Keyboard,
Form, IonicModule, DomController
} from 'ionic-angular';
import {
mockConfig, mockDomController, MockPlatform, mockPlatform
} from 'ionic-angular/util/mock-providers';
,因此更新的beforeEach
应该以
TestBed.configureTestingModule({
schemas: [CUSTOM_ELEMENTS_SCHEMA],
declarations: [FooPage],
providers: [
App,
Form,
Keyboard,
{ provide: Platform, useClass: MockPlatform },
{ provide: DomController, useValue: mockDomController(mockPlatform()) },
{ provide: Config, useValue: mockConfig() },
],
imports: [
FormsModule,
IonicModule,
ReactiveFormsModule
],
});
pr带有上述示例已合并到https://github.com/marcoturi/ionic-boilerplate。