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 !

3
  • Your problem is that even though you updated the value, it doesn't automatically trigger the html form validators to check again. stackoverflow.com/questions/32260082/… Commented Mar 10, 2020 at 13:59
  • [update] Even if we call updateValueAndValidity(), I have the same result. Commented Mar 10, 2020 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. Commented Mar 10, 2020 at 14:36

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.