我有以下组件模板:
li
在我的测试中,我想测试错误状态。但是,我需要在测试中访问输入控件“ #checkbox”并将其设置为脏。
var html = "";
html += `<ul id="myUL">`;
for(var x = 0; x < jsonArr.length; x++){
html += `
<li customerId = "${jsonArr[x].customerId}">
<a href="#"><strong>Customer Name:</strong> ${jsonArr[x].customerName}
<br><strong>Main Phone:</strong> ${jsonArr[x].mainPhone}
<br><strong>Main Email:</strong> ${jsonArr[x].mainEmail}
<br><strong>Bill To Address:</strong> ${jsonArr[x].mainBillTo1},
<br>${jsonArr[x].mainBillTo2},
<br>${jsonArr[x].mainBillTo3}
<br></a>
<input type="button" class= "btnEdit" value="EDIT">
</li>`;
}
html += `</ul>`;
如果将ViewChild添加到我的组件中,则可以在测试中访问它:
<div>
<mat-checkbox [(ngModel)]="model.value" required="true" #checkbox="ngModel">{{model.title}}</mat-checkbox>
<mat-error *ngIf="checkbox.invalid && checkbox.dirty">Some Error</mat-error>
</div>
但是,我想在测试中访问模型,而无需向组件本身添加变量,因为从未使用过该模型。
编辑:我也尝试过修改值以将控件切换为脏:
it('should show error on invalid', () => {
const checkbox = fixture.debugElement.query(By.directive(MatCheckbox))
// I have the mat-checkbox, however not sure how to access the form control to set as dirty
})
答案 0 :(得分:2)
我能够按以下方式抓取模型:
const model = fixture.debugElement.query(By.directive(MatCheckbox)).references['checkbox']
然后标记为脏
model.control.markAsDirty()
答案 1 :(得分:-1)
您不能直接使用该特定控件本身的ID进行检查Fixture.debugElement.query(By.css(“#id”))。markAsDirty()