gpt4 book ai didi

react 形式的 Angular Testing 提交事件

转载 作者:太空狗 更新时间:2023-10-29 17:46:26 31 4
gpt4 key购买 nike

上下文

我有一个具有基本形式( react 形式)的组件。我尝试测试此表单上的提交事件,看它是否正确调用了必要的方法。

我的问题

无法触发表单的提交事件

文件

组件.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');
}

组件.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);

那么如何触发表单提交事件呢?

最佳答案

第一个选项是直接调用 ngSubmit:

.triggerEventHandler('ngSubmit', null); 

第二个选项是导入 ReactiveFormsModule,它将在表单上内部设置 submit 处理程序。所以你的触发方法应该有效:

TestBed.configureTestingModule({
declarations: [
MyComponent
],
imports: [ReactiveFormsModule], // <== import it
providers: []

关于 react 形式的 Angular Testing 提交事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43527202/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com