0
角度v4.4.4を使用して、<form>
要素の(submit)
イベントを使用してフォームを保存しています。ライブコードではすべて正常に動作します。しかし、ユニットテストで<button>
をクリックしても(submit)
がトリガーされず、テストに失敗します。例えば、使用時に角度単位テストに失敗する
成分(擬似コード):
@Component({
template: `
<form [formGroup]="formGroup" (submit)="onSave()">
Your name: <input type="text" formControlName="name">
<button id="saveButton">Save</button>
</form>
`
})
export class FooComponent {
public formGroup: FormGroup;
public onSave(): void {
// save and route somewhere
}
}
ユニットテスト(擬似コード):
describe('FooComponent',() => {
let fixture, component, _router, routerSpy;
beforeAll(done => (async() => {
TestBed.configureTestingModule({
imports: [
RouterTestingModule.withRoutes([]),
FormsModule,
ReactiveFormsModule
]
});
fixture = TestBed.createComponent(FooComponent);
component = fixture.componentInstance;
_router = fixture.debugElement.injector.get(Router);
routerSpy = spyOn(_router, 'navigate');
fixture.detectChanges();
})().then(done).catch(done.fail));
it('should save the form',() => {
const saveButton = fixture.debugElement.query(By.css('#saveButton'));
saveButton.triggerEventHandler('click', null);
expect(routerSpy).toHaveBeenCalled();
// the test fails because the form is not actually submitted
});
});
I問題が(submit)
イベントである確信して私は削除するためそれはonSave()
コールを(click)
に移動して、単体テストのボタンが動くようにします。
だからこれは、ユニットテストで失敗します。
<form [formGroup]="formGroup" (submit)="onSave()">
しかし、これは成功します。
<button id="saveButton" (click)="onSave()">Save</button>
を私はスペックに間違っ何をしているのですか?
パーフェクト。ありがとうございました。 – ebakunin