【发布时间】:2020-09-16 14:12:33
【问题描述】:
您好,我正在使用 Angular 并尝试为响应式表单创建单元测试但无法成功
我需要什么:如何在表单中使用 jasmine in angular 填充虚假和真实值后执行按钮单击。
我做了什么:我创建了一个逻辑,但它不起作用
it('Form check is valid or not if no values entered', () => {
expect(component.userCreationForm.valid).toBeFalsy();
});
it('Form check is valid or not when values entered', () => {
component.userCreationForm.controls['firstname'].setValue('luther');
component.userCreationForm.controls['lastname'].setValue('adams');
component.userCreationForm.controls['email'].setValue('test@gmail.com');
component.userCreationForm.controls['password'].setValue('123456');
expect(component.userCreationForm.valid).toBeTruthy();
});
it('Form Submitted should check from is submitted', () => {
// check form is invalid
expect(component.userCreationForm.invalid).toBeTruthy();
let btn = fixture.debugElement.query(By.css('button[type=submit]'));
// Check button is disabled
expect(btn.nativeElement.disabled).toBeTruthy();
component.userCreationForm.controls['firstname'].setValue('luther');
component.userCreationForm.controls['lastname'].setValue('adams');
component.userCreationForm.controls['email'].setValue('test@gmail.com');
component.userCreationForm.controls['password'].setValue('testpassword');
fixture.detectChanges();
// check button is enabled
expect(btn.nativeElement.disabled).toBeFalsy();
component.onUserCreation();
fixture.detectChanges();
let success = fixture.debugElement.query(By.css('#success-msg')).nativeElement;
expect(success.textContent).toBe('Bubba');
});
html逻辑
<div class="inv-buttons">
<button mat-raised-button color="primary" [disabled]="userCreationForm.invalid" type="submit">Create User</button>
</div>
下面是我的堆栈闪电战:https://stackblitz.com/edit/angular-9-material-starter-q9wxvq
【问题讨论】:
-
好吧,如果我理解正确,您不会在任何地方调用 click。您只是在检查按钮的启用/禁用状态。检查后尝试
btn.click(),如果它已启用。 -
@dallows 你能指点我吗?
-
在
expect(btn.nativeElement.disabled).toBeFalsy();下方添加btn.click() -
出现错误,因为“DebugElement”类型上不存在属性“click”
标签: javascript angular jasmine karma-jasmine