我在模板驱动表单中有一个角度输入。
<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>
我如何进行单元测试,它只能输入maxlength为20的文本。
我的组件中有这个:
export class PacienteDialogComponent implements OnInit {
paciente: Paciente;
constructor( //other things not paciente
){
}
.....
这是我的paciente.model.ts,它具有我想测试的输入tarjetaSanitaria的属性:
import { BaseEntity } from './../../shared';
export class Paciente implements BaseEntity {
constructor( public tarjetaSanitaria?: string)
{
}
}
这是我的测试课:
import { Paciente } from...
import { PacienteDialogComponent } from '..
describe(....){
let comp: PacienteDialogComponent;
let fixture: ComponentFixture<PacienteDialogComponent>;....
beforeEach(() => {
fixture = TestBed.createComponent(PacienteDialogComponent);
comp = fixture.componentInstance;...
it ('Input validation', async(() => {
comp.cardInput.nativeElement.value = 'dddddddddddddddddddddddddddddddddddddddddddddddddddddd' ; // a text longer than 20 characters
expect(comp.cardInput.nativeElement.valid).toBeFalsy();
}));
测试通过,但无论如何这是测试输入验证的正确方法吗? toBeFalsy()之后会发生什么?用户怎么知道这是假的?如果是错误,我可以输出消息吗?
有没有其他方法可以测试表单输入验证?
答案 0 :(得分:3)
测试有效,因为它依赖于虚假值。
尝试使用:
expect(comp.cardInput.nativeElement.valid).toEqual(false);
expect(comp.cardInput.nativeElement.invalid).toEqual(true);
expect(comp.cardInput.nativeElement.invalid).toBeTruthy();
它们都不会起作用。
comp.cardInput.nativeElement
代表HTMLElement
。它包含className
,onclick
,querySelector
等属性。
valid
不是HTML标准的一部分:它是一个Angular概念。
这意味着当你写
expect(comp.cardInput.nativeElement.valid).toBeFalsy()
输出到
expect(undefined).toBeFalsy()
这是真的,因为undefined是假的。
测试此方法的正确方法是测试元素是否包含特殊的Angular类ng-invalid
(或测试它不包含ng-valid
)。
在提供代码之前,我建议你切换到被动形式,它们更强大,更容易测试。
但无论如何,这就是你如何做到的。
it('should be invalid given a value of over 20 chars', () => {
// NEVER use the nativeElement to set values. It's bad practice.
component.paciente.tarjetaSanitaria = 'dddddddddddddddddddddddddd';
// Detect changes, it's not automatic
fixture.detectChanges();
// Test (bad practice)
expect(component.cardInput.nativeElement.className.includes('ng-invalid').toEqual(true);
// Test (good practice)
expect(fixture.nativeElement.querySelector('input[name="tarjetaSanitaria"]').className.includes('ng-invalid')).toEqual(true);
});