【发布时间】:2017-09-17 12:58:58
【问题描述】:
上下文
我有一个具有基本形式(反应形式)的组件。我尝试在这个表单上测试提交事件,看看它是否正确调用了必要的方法。
我的问题
我无法触发表单的提交事件
文件
组件.html
<form class="form-horizontal"
id="staticForm"
[formGroup]="mySimpleForm"
(ngSubmit)="sendMethod();"
>
<input type="text" formGroupName="email">
<button type="submit">Send form</button>
</form>
组件.ts
ngOnInit() {
this.initSimpleForm();
}
private initSimpleForm() {
let file = null;
this.mySimpleForm = this.formBuilder.group({
email: [
'',
[
Validators.required
]
]
});
}
sendMethod() {
console.log('submitted');
}
component.spec.ts
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
MyComponent
],
imports: [],
providers: [
FormBuilder
],
schemas: [NO_ERRORS_SCHEMA]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(MyComponent);
comp = fixture.componentInstance;
});
it(`should notify in console on form submit`, () => {
spyOn(console, 'log');
comp.mySimpleForm.controls['email'].setValue('test@test.com');
fixture.debugElement.query(By.css('form')).triggerEventHandler('submit', null);
fixture.detectChanges();
expect(console.log).toHaveBeenCalled(); // FAILS
});
// TO make sure my spy on console log works, I made this and it works
it(`will notify on direct sendMethod Call`, () => {
spyOn(console, 'log');
comp.sendMethod();
fixture.detectChanges();
expect(console.log).toHaveBeenCalled(); // SUCCESS
});
我也尝试过,而不是在表单上调用submit:
fixture.debugElement.query(By.css('button')).triggerEventHandler('click', null);
那么如何触发表单提交事件呢?
【问题讨论】:
标签: angular typescript jasmine karma-runner karma-jasmine