vest icon indicating copy to clipboard operation
vest copied to clipboard

Multiple groups using same tests function

Open mellondev opened this issue 6 months ago • 2 comments

Is it possible to reuse a validation suite multiple times using groups.

The scenario I have is a company details model has 2 different addresses, the validation is the same for each address so rather than duplicating the tests I tried to reuse as below:

import { create, enforce, group, only, test } from 'vest';

export const companyValidationSuite = create(
  'companyValidationSuite',
  (model, field?) => {
    only(field); // if field defined, limit to tests of this field

    test('name', 'Name is required', () => {
      enforce(model.name).isNotEmpty();
    });

    group('billingAddress', () =>
      companyAddressValidations(model.billingAddress!)
    );

    group('officeAddress', () =>
      companyAddressValidations(model.officeAddress!)
    );
  }
);

export const companyAddressValidations = (model: any) => {
  test('line1', 'Line 1 is required', () => {
    enforce(model.line1).isNotEmpty();
  });

  test('city', 'City is required', () => {
    enforce(model.city).isNotEmpty();
  });

  test('postCode', 'Post Code is required', () => {
    enforce(model.postCode).isNotEmpty();
  });
};

If I then execute the suite as below, it only returns errors for the first group a total of 4 errors but there is 7 errors as both address groups have errors, it shows the field name and groupname in the errors array:

    const result = companyValidationSuite({});
    console.log(result);

If I then supply a value for one of the fields in one of the address (as below), the result is the same number of errors (4) but this time there are 2 errors for the billingAddress group and 1 error for the officeAddress group.

    const result = companyValidationSuite({ billingAddress: { line1: 'test' }});
    console.log(result);

mellondev avatar Jan 03 '24 17:01 mellondev