2

i am trying to write some unit tests for my project and I needed some help about it. I have an input and i want to verify that it accepts only numbers/digits, otherwise it should be invalid.

TS:

this.form = this.formBuilder.group({
        inputNumber: [null, [Validators.required, Validators.min(0)]]});

HTML Template:

<mat-form-field>
<input matInput placeholder="pls give a number" type="number" step="1" formControlName="inputNumber">
</mat-form-field>

Unit Test (*.spec.ts):

it('FormControl only accepts numbers', () => {
        let inputNumber = component.form.controls['inputNumber'];
        inputNumber.setValue(null);
        console.log('Valid :', inputNumber.valid);//valid: false (required)

        inputNumber.setValue('any string or !number');
        expect(inputNumber.valid).toBe(false);//but returns TRUE
});

thanks !

  • Your problem is that even though you updated the value, it doesn't automatically trigger the html form validators to check again. https://stackoverflow.com/questions/32260082/does-anybody-know-how-to-trigger-form-validators-in-angular2 – canpan14 Mar 10 '20 at 13:59
  • [update] Even if we call updateValueAndValidity(), I have the same result. – Théo Esnault Mar 10 '20 at 14:22
  • 1
    The `FormControl` is not aware of element attributes like `type`. You need a validator if you want the control to know that non-numeric input is invalid. – The Head Rush Mar 10 '20 at 14:36

2 Answers2

0

I once had a similar problem, which is that formControl does not even distinguish between number and/or any other field.

Ended up creating my own Control

export class NumberControl extends FormControl {
    _value: number | undefined;
    get value() {
      return this._value;
    }

    set value(value) {
      this._value = (value || value === 0) ? Number(value) : undefined;
    }
  }

which than can be used like

 formControl = new NumberControl('', field.validator);

That way you can make sure you either get a number or undefined.

Hope it helps

djnose
  • 917
  • 7
  • 19
0

I think you have to add pattern validation Validators.pattern(/\d/)

Like this

this.form = this.formBuilder.group({
        inputNumber: [null, [Validators.required,Validators.pattern(/\d/), Validators.min(0)]]});

because angular reactive form doesn't consider html validation in all cases

Ahmed Kesha
  • 810
  • 5
  • 11