Validating schema using AJV

I’m trying to validate this scheme and don’t understand why it failed.

{
“id”: 1,
“displayName”: “Age”,
“createdAt”: “2021-07-06T19:22:10Z”,
“modifiedAt”: “2021-07-06T19:22:10Z”
}

var Ajv = require(‘ajv’),
ajv = new Ajv({
logger: console,
allErrors: true,
verbose: true
}),
schema = {
“type”: “object”,
“properties”: {
“id”: {
“type”: “integer”
},
“displayName”: {
“type”: “string”
},
“createdAt”: {
“type”: “string”
},
“modifiedAt”: {
“type”: “string”
}
},
“required”: [
“id”,
“displayName”,
“createdAt”,
“modifiedAt”
]
};

pm.test(‘Schema is valid’, function () {
var data = pm.response.json();
pm.expect(ajv.validate(schema, data), printErrors(ajv)).to.be.true;
});

Hi @tvu

What failure do you see?
I’m guessing you are seeing:

Schema is valid | ReferenceError: printErrors is not defined

This is because you are using “printErrors” without declaring the function.

Add this to the top of your test script:

function printErrors(ajv){
    if(ajv.errors !== null){
        console.log(JSON.stringify(ajv.errors[0]));    
    }
}

Example working:

Oh shoot I forgot about the function! Thank you