ANGULAR TESTING - Form Input type="number" should only accept numbers

Viewed 1668

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 !

2 Answers

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

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

Related