Nikita S
Nikita S

Reputation: 137

What is Expect function to validate schema in JEST and Supertest?

like in chakram testing expect(WallObject).to.have.schema(expectedSchema). Similarly which function is there in Jest? I am using jest with supertest.

Upvotes: 0

Views: 4166

Answers (2)

2Max
2Max

Reputation: 337

I recently used jest-json-schema

Very easy to use.

import { matchers } from 'jest-json-schema';
expect.extend(matchers);

it('validates my json', () => {
  const schema = {
    properties: {
      hello: { type: 'string' },
    },
    required: ['hello'],
  };
  expect({ hello: 'world' }).toMatchSchema(schema);
});

Upvotes: 0

Nikita S
Nikita S

Reputation: 137

There is nothing available in JEST to test schema directly. I have achieved this with the help of AJV. Using AJV i am comparing schema with response and then using Jest expect checking value is true or not. like

const Ajv = require('ajv');

const ajv = new Ajv({
  allErrors: true,
  format: 'full',
  useDefaults: true,
  coerceTypes: 'array',
  errorDataPath: 'property',
  sourceCode: false,
});

const validateParams = (params, schema) => {
  const validate = ajv.compile(schema);
  const isValidParams = validate(params);
  return isValidParams;
};

 const result = validateParams(res.body, {
        type: 'array',
        items: {
          type: 'object',
          properties: {
            id: {
              type: 'integer',
            },
            email: {
              type: 'string',
            },
         }
      }
    });

 expect(result).toBe(true);
 done();

Upvotes: 1

Related Questions