我正在以角度测试模板驱动的表单,只是测试而不验证它。我读过可以使用 viewChild 属性来完成,但它似乎对我不起作用。
我在我的一个表单标签中创建了这样的引用:
<label #ref id=.. class=...>
Run Code Online (Sandbox Code Playgroud)
现在在我的组件中我这样做:
@ViewChild('ref') ref:ElementRef;
Run Code Online (Sandbox Code Playgroud)
所以,我想我创建了一个 ElementRef 类型的变量,它是我输入的 viewChild 。所以现在我可以在测试中使用ref 。
在我的测试中我这样做:
<label #ref id=.. class=...>
Run Code Online (Sandbox Code Playgroud)
现在考虑测试、html 和组件文件是相互分离的。
我仍然收到无法读取 nativeElemnt 属性的错误。 尽管我已经导入了 ElemntRef。
这是访问 DOM 元素的正确方法吗?或者这个 viewChild 没有引用我的标签?
我可以再次使用 ID 来访问表单元素吗?我读到的内容是使用带有 # 的引用。
谢谢!!
我在模板驱动的表单中有一个 angular 输入。
<form name="editForm" role="form" novalidate (ngSubmit)="save()" #editForm="ngForm">
<input #cardInput type="text" class="form-control" name="tarjetaSanitaria" id="field_tarjetaSanitaria"
[(ngModel)]="paciente.tarjetaSanitaria" maxlength="20"/>
<small class="form-text text-danger"
[hidden]="!editForm.controls.tarjetaSanitaria?.errors?.maxlength" jhiTranslate="entity.validation.maxlength" translateValues="{ max: 20 }">
This field cannot be longer than 20 characters.
</small>
Run Code Online (Sandbox Code Playgroud)
我如何单元测试它只能输入最大长度为 20 的文本。
我的组件中有这个:
export class PacienteDialogComponent implements OnInit {
paciente: Paciente;
constructor( //other things not paciente
){
}
.....
Run Code Online (Sandbox Code Playgroud)
这是我的 paciente.model.ts,它具有我想要测试的输入 tarjetaSanitaria 的属性:
import { BaseEntity } from './../../shared';
export class Paciente implements BaseEntity {
constructor( public tarjetaSanitaria?: string)
{
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的测试课:
import …Run Code Online (Sandbox Code Playgroud)