Here是一个类似的问题,从未得到回答。
我有一个登录页面,可以通过单击或输入框中的Enter键触发login()
方法(因为它使用的是ngSubmit)。
<form [formGroup]="loginForm" (ngSubmit)="login()">
我的第一个测试(检查单击按钮时是否触发login())传递正常,如下所示:
it('should trigger login() method when username & password are entered, then button is clicked', () => {
spyOn(component, 'login');
component.loginForm.controls['username'].setValue('123');
component.loginForm.controls['password'].setValue('123');
fixture.detectChanges();
const loginButtonElm: HTMLButtonElement = fixture.debugElement.query(By.css('button.slds-button')).nativeElement;
loginButtonElm.click();
fixture.whenStable().then(() => {
expect(component.login).toHaveBeenCalled();
})
});
现在我想检查一下Enter键是否也可以触发login()方法,但是我尝试过的每一个测试都失败了,并且在网上没有这个好的答案。这是我试过的:
It('should trigger login() method when username & password are entered, then \'Enter\' key is pressed', async(() => {
spyOn(component, 'login');
component.loginForm.controls['username'].setValue('123');
component.loginForm.controls['password'].setValue('123');
fixture.detectChanges();
const pressEnter = new KeyboardEvent('keypress', {'key': 'Enter'});
fixture.nativeElement.dispatchEvent(pressEnter);
fixture.detectChanges();
fixture.whenStable().then(() => {
expect(component.login).toHaveBeenCalled();
})
}));
答案 0 :(得分:0)
确定按键试试这个,尝试一下然后告诉我,但是当我回到家的时候我会创建一个代码示例;)
It('should trigger login() method when username & password are entered, then \'Enter\' key is pressed', async(() => {
spyOn(component, 'login');
component.loginForm.controls['username'].setValue('123');
component.loginForm.controls['password'].setValue('123');
fixture.detectChanges();
const event: Event = new KeyboardEvent('keypress', {'key': 'Enter'});
window.dispatchEvent(event);
fixture.detectChanges();
fixture.whenStable().then(() => {
expect(component.login).toHaveBeenCalled();
})
}));