0

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.
    });
});
hofshteyn
  • 1,272
  • 4
  • 16
  • 33
  • What happens if you call `fixture.whenStable` again after `setValue`. – Reactgular Dec 24 '18 at 14:32
  • 1
    May be you will have to call `form.get('speed').updateValueAndValidity()` after setting form control value – Amit Chigadani Dec 24 '18 at 14:43
  • hofshteyn did you managed to find a solution to this? – cp5 Jan 08 '21 at 23:22
  • @Chrispie Solved, but actually I don't remember how. Sorry about that :( – hofshteyn Jan 12 '21 at 10:49
  • @Chrispie https://stackoverflow.com/questions/65645144/testing-angular-component-form-for-pristine-is-not-working Good answer to this question. To change the `pristine` value, the input has to come from the HTML and not from `setValue`. – AliF50 Jun 09 '21 at 18:59

1 Answers1

1

try using this

let form = fb.group({
speed : ['']
});
form.controls.speed.setValue('10');
expect(form.pristine).toBeFalsy();

if you want to check error you can write this instead :

expect(form.controls.speed.valid).toBe(false);
Ushmi Dave
  • 276
  • 1
  • 7