ajv
ajv copied to clipboard
JSON Schema exemple not working with jest
ajv version: "^8.11.0"
It doesn't even compile :(
//schema.spec.ts
test('', async () => {
interface MyData {
foo: number
bar?: string
}
const schema: JSONSchemaType<MyData> = {
type: 'object',
properties: {
foo: { type: 'integer' },
bar: { type: 'string', nullable: true }
},
required: ['foo'],
additionalProperties: false
}
// validate is a type guard for MyData - type is inferred from schema type
ajv.compile(schema)
})
Console:
schema is invalid: data/type must NOT have additional properties, data must have property 'ref', data/type must be equal to one of the allowed values, data must have property 'enum', data must have property 'elements', data/properties/foo/type must NOT have additional properties, data/properties/foo must have property 'ref', data/properties/foo/type must be equal to one of the allowed values, data/properties/foo must have property 'enum', data/properties/foo must have property 'elements', data/properties/foo must have property 'properties', data/properties/foo must have property 'optionalProperties', data/properties/foo must have property 'discriminator', data/properties/foo must have property 'values', data/properties/foo must match a schema in union, data must have property 'optionalProperties', data must have property 'discriminator', data must have property 'values', data must match a schema in union
Try remove async key word.
do you have strict (or strictNullChecks) mode enabled in TypeScript?
I have the same issue unfortunately
I'm experiencing a similar thing; I noticed that I get this error when I add "type": "object" to any of my schemas.
I had a similar issue which was resolved by explicitly using the 2020 draft schema. My error message was something like:
schema is invalid: data must have required property 'something', schema is invalid: data must have required property 'somethingElse', data must NOT have additional properties, data must NOT have additional properties
My Fix
schema
I updated the schema to add the "$schema" property:
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"properties": {...},
"required": [...],
"additionalProperties": false
}
typescript
I then updated the code in my .ts file to import Ajv from /dist/2020 so the 2020-12 draft schema is recognized:
import mySchema from '@/mySchema.json';
import Ajv from 'ajv/dist/2020';
const ajv = new Ajv({ allErrors: true });
const validator = ajv.compile(mySchema); // works!