Recently sorry if it's a duplicate of any questiom. I didn't find any solution for my problem.
So I have a form with one input field. When I'm fetching data in onInit
I put the value inside this field and make it pristine. After I change value manually form becomes dirty and I make some actions.
It works in component but I can't properly test it. After I make setValue()
for input field it stayed pristine (in test). But I need to emulate the real input and forms pristine should becomes false
.
component.ts
ngOnInit() {
this.form = this.fb.group({
speed: this.fb.control(null)
});
this.service.getData().pipe(takeUntil(this.destroyed$))
.subscribe(info => {
this.info = info;
this.updateForm();
});
}
updateForm() {
this.form.patchValue({
speed: this.info.speed
});
this.form.get('speed').setValidators([
Validators.required,
Validators.pattern('^[0-9]*$'),
]);
this.form.markAsPristine();
}
component.spec.ts
beforeEach(() => {
fixture = TestBed.createComponent(component);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy(); // passed
});
it('should make form dirty', () => {
component.info = generateInfo();
fixture.detectChanges();
component.updateForm();
fixture.whenStable().then(() => {
expect(component.form.pristine).toBeTruthy();
expect(component.form.get('speed').value).toBe(20);
component.form.controls['speed'].setValue(10);
expect(component.form.pristine).toBeFalsy(); //error Expected true to be falsy.
});
});