Test for an AJV-based middleware fails

Viewed 108

I am trying to create a middleware that validates data send to my Firebase HTTPS functions. It's meant to simply take the data, check it, pass it through if it is valid and throw an HttpsError when it is invalid (plus it throws an error if for whatever reason the schema can't be loaded).

The Test

This loads a valid schema but submits invalid data:

  it("should fail with an error when submitting invalid data", () => {
    const middleware = createValidationMiddleware("customer.schema.json");
    expect(() => middleware({})).toThrow(HttpsError);
  });

The Validation Script

export const createValidationMiddleware: (schema: Schemas) => Middleware =
  (schema) => (data, context, next) => {
    const validate = ajv.getSchema(schema);

    if (!validate)
      throw new HttpsError(
        "failed-precondition",
        `schema ${schema} does not exist`
      );

    if (!validate(data))
      throw new HttpsError(
        "invalid-argument",
        `The data is invalid: ${validate.errors}`
      );

    return next(data, context);
  };

The Error

I can see in the terminal all the AJV validation errors, i.e.:

ValidationError: validation failed

The test fails with:

 FAIL  src/middlewares/validation.test.ts
  ● Test suite failed to run

    Jest worker encountered 4 child process exceptions, exceeding retry limit

      at ChildProcessWorker.initialize (node_modules/jest-worker/build/workers/ChildProcessWorker.js:170:21)

I think the problem might be the ValidationErrors thrown by AJV, and I tried wrapping the validate(data) in a try / catch, but the error was the same, and Google hasn't been particularly helpful...

0 Answers
Related