summaryrefslogtreecommitdiff
path: root/spec/frontend/__helpers__/matchers/to_validate_json_schema.js
blob: ff391f08c55192d8cff5238057e814c03bc7b453 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
// NOTE: Make sure to initialize ajv when using this helper

const getAjvErrorMessage = ({ errors }) => {
  return (errors || []).map((error) => {
    return `Error with item ${error.instancePath}: ${error.message}`;
  });
};

export function toValidateJsonSchema(testData, validator) {
  if (!(validator instanceof Function && validator.schema)) {
    return {
      validator,
      message: () =>
        'Validator must be a validating function with property "schema", created with `ajv.compile`. See https://ajv.js.org/api.html#ajv-compile-schema-object-data-any-boolean-promise-any.',
      pass: false,
    };
  }

  const isValid = validator(testData);

  return {
    actual: testData,
    message: () => {
      if (isValid) {
        // We can match, but still fail because we're in a `expect...not.` context
        return 'Expected the given data not to pass the schema validation, but found that it was considered valid.';
      }

      const errorMessages = getAjvErrorMessage(validator).join('\n');
      return `Expected the given data to pass the schema validation, but found that it was considered invalid. Errors:\n${errorMessages}`;
    },
    pass: isValid,
  };
}