【发布时间】:2017-05-30 19:16:48
【问题描述】:
我正在尝试用量角器测试我的应用中输入表单的验证代码。
我的组件看起来或多或少是这样的:
@Component({
selector: 'app-my-component',
templateUrl: './my-component.component.html',
styleUrls: ['./my-component.component.css']
})
export class MyComponent implements OnInit {
private myForm: FormGroup;
private category: AbstractControl;
constructor(fb: FormBuilder) {
this.myForm = fb.group({
'category': ['', Validators.required]
});
this.category = this.myForm.controls['category'];
}
...
}
在这个简化版本类别中是我的表单的only 输入字段。
依次my-component.component.html:
<form [formGroup]="myForm" class="new-item-form">
<input type="text" name="category" title="Hochladen"
placeholder="Enter a category"
[formControl]="category">
category.isValid = <pre>{{category.valid | json}}</pre>
<br>
category.value<pre class="test">{{category.value | json}}</pre>
<br>
<div *ngIf="!category.valid && (!category.pristine)"
class="ui error message">Document category not valid</div>
</form>
... 换句话说,显示文档类别无效的文本仅在表单域已播放但仍为空白时才会显示。到目前为止一切顺利,直到这里它也运行良好。 pre 标记只是一种帮助,因此可以直观地提醒正在发生的事情。
当我尝试使用量角器测试这种行为时,真正的问题出现了。在这种情况下,给定 app.e2e-spec.ts:
describe('Form validation', () => {
it('should show missing category validation error if category is missing after field edited', () => {
page.navigateTo();
let categoryInput = element(by.css('form.new-upload-form input[name="category"]'));
categoryInput.sendKeys('abc');
expect(categoryInput.getAttribute('value')).toBe('abc');
categoryInput.clear();
expect(categoryInput.getAttribute('value')).toBe('');
let errorMessages = element.all(by.css('.ui.error.message'))
expect(errorMessages.count()).toBe(1);
});
});
除了最后一个ie之外,所有的expect调用都会成功。 expect(errorMessages.count()).toBe(1);。这意味着永远不会显示错误消息。
只有在量角器操作时才会发生这种情况。只要这是真的,category.isValid 总是正确的。在最初的categoryInput.sendKeys('abc'); 之后,category.value 保持始终为'abc'。
我尝试了一堆categoryInput.click(); 或bodyElement.click() 无济于事。我也尝试过使用几个categoryInput.sendKeys('\ue003');(backspace) 来代替/添加categoryInput.clear()。同样,仅输入 '\ue003'(而不是 'abc')不会对 category.pristine 产生任何影响(也不应该)。
为了寻求知识,我将继续阅读ReactiveFormsModule 的源代码,以了解categoryInput.sendKeys(...) 或categoryInput.clear 是如何被忽略的。
在我忘记之前,我正在使用 protractor = 5.1.0、@angular/cli = 1.0.0、@angular/common = 4.0.0 ... @angular/forms = 4.0.0
感谢您来到这里,如果您认为可以提供帮助,那就更是如此。
【问题讨论】:
-
您在
categoryInput.clear();之后尝试拨打categoryInput.sendKeys("")吗?我认为另一个想法可能是提交表单,这可能吗? -
组件上有可以触发的事件吗?例如,在使组件为空后,在组件上执行
blur。据我从您的描述中了解到,这不是现在发生的情况。 -
感谢@Batajus,
categoryInput.sendKeys("")在categoryInput.clear()之后没有帮助。我现在正试图绕过整个“原始”代码,以使其正常工作。 -
感谢@wswebcreation,我已经尝试
blur通过单击输入字段外部(禁用的提交按钮),但它似乎没有帮助。我曾尝试在categoryInput字段上触发“输入”事件,但我不知道如何使用量角器来做到这一点。
标签: angular protractor angular-cli angular2-forms