0

I'm using ngx-formly (on V5) to generate a form with an input and a checkbox (here is the FormlyFieldConfig):

field: FormlyFieldConfig = {
className: 'database-header',
validators: {
  validation: [
    { name: 'maxLengthIfExternal', options: { errorPath: 'name' } },
  ],
},
fieldGroup: [
  {
    className: 'align-left',
    key: 'name',
    type: 'input',
    defaultValue: '',

    templateOptions: {
      required: true,
      label: 'Database Name',
      pattern: HYPHEN_REGEX_PATTERN_VALIDATION,
      maxLength: 32,
    },
    validation: {
      messages: {
        pattern:
          'Allowed characters: a-z 0-9 -, must start with lower case letter and end with an alphanumeric character',
      },
    },
  },
  {
    key: 'external',
    type: 'checkbox',
    templateOptions: {
      label:
        'External',
    },
  },
],

};

I have a custom validator that is checking if the checkbox is checked (maxLengthIfExternal). If it is, the name input cannot be more than 8 characters.

I want to unit test (jest) the validation for this form: setting the input to more then 8 characters then clicking the checkbox and checking that the form is now invalid.

I can't find any documentation on how to unit test validation on formly. Does anyone know how to achieve that?

1 Answer 1

1

You can do so with testing library, as long as you have some visual cue when the form is invalid. For example, let's say we have a submit button that will only be enabled if the form is valid. You could write the test like this:

it('should be invalid if the input value has more than 8 chars and the checkbox is ticked', () => {
  const input = screen.getByRole('input')
  const checkbox = screen.getByRole('checkbox')

  userEvent.type(input, '123456789')
  userEvent.click(checkbox)

  expect(screen.getByRole('button', { name: /submit/i  })).shouldBeDisabled()
})

You can write a similar test using Angular testing selectors, it's just a different interface.

2
  • This is not going to work because of formly. Unless there is a way to build the form within the unit test itsefl, and this is what I'm serching for.
    – Sa Hagin
    Oct 24, 2022 at 7:02
  • I don't get it. Why wouldn't it work with formly?
    – Allan Juan
    Oct 24, 2022 at 12:08

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.