Это будет во многом зависеть от того, как вы создаете свою форму, но я могу написать тест, который подтверждает правильность формы так, как я думаю, вы пытаетесь. Мне нужно увидеть тестируемый компонент, чтобы знать наверняка.
Вот фрагмент стека, показывающий эти тесты .
app.component.ts:
export class AppComponent implements OnInit {
myForm: FormGroup;
//Helper to get the username control to check error state
get username() {
return this.myForm.get('username');
}
constructor(private fb: FormBuilder) {
}
ngOnInit() {
//"Username" has two validations to test: required and minLength
this.myForm = this.fb.group({
'username': new FormControl(null, [Validators.required, Validators.minLength(10)])
});
}
}
app.component. html:
<form [formGroup]="myForm">
<!-- "username" input with conditional styles based on error state -->
<input type="text"
formControlName="username"
[class.username-valid]="!username.errors"
[class.error-username-required]="username.errors?.required"
[class.error-username-minlength]="username.errors?.minlength">
</form>
app.component.spe c .ts:
describe('AppComponent', () => {
let fixture: ComponentFixture<AppComponent>;
let component: AppComponent;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
FormsModule,
ReactiveFormsModule
],
declarations: [
AppComponent
],
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(AppComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
describe('The form validity', () => {
const testCases = [
{
expected: true,
username: 'VALID_USERNAME',
expectedCss: 'username-valid'
},
{
expected: false,
username: null,
expectedCss: 'error-username-required'
},
{
expected: false,
username: 'too_short',
expectedCss: 'error-username-minlength'
}
];
testCases.forEach(testCase => {
it(`should update the form validity: ${testCase.expected}`, () => {
component.myForm.get('username').setValue(testCase.username);
component.myForm.updateValueAndValidity();
fixture.detectChanges();
expect(component.myForm.valid).toBe(testCase.expected); //assert the form is valid/invalid
expect(fixture.debugElement.query(By.css(`.${testCase.expectedCss}`))).toBeTruthy(); //assert the conditional style is applied
});
});
});
});