Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting error type/value when validating json schema with ajv

I'm trying to use json schema to validate the json of an api.

I've found the ajv library, which seems to be the most popular for node.js.

Just getting the basics, I've defined my schema as

const viewSchema = {
    "type": "object",
    "properties":{
        "title": {"type": "string"}
    }
}

export default viewSchema;

I then import it into my validator

import Ajv from 'ajv';

import viewSchema from './viewSchema';
const ajv = Ajv({allErrors: true});
let validate = ajv.compile(viewSchema);

const validateView = viewJson => {
    var isValid = validate(viewJson);
    console.log('------ text',ajv.errorsText(), isValid)
    if(isValid) return true;
    return ajv.errorsText();
}

export default validateView;

and using mocha (with mochaccino) test the output

describe('validate view', () => {
    it('should error if title is not a string', () => {
        console.log('-----------',validateView({"title":122}))
        expect(validateView({"title":122}).errors).toContain('should be string');
    });
});

following the directions from the ajv github page I expect my test to fail as the type required is a string and I've provided a number. But the response I'm getting from ajv.errorsText() is No Errors where it should provide an error.

Seems so simple, what am I doing wrong?

like image 426
pedalpete Avatar asked Sep 15 '25 19:09

pedalpete


1 Answers

You need to pass errors to ajv.errorsText():

ajv.errorsText(validate.errors)

Without parameter it would return errors text if you use method ajv.validate.

See https://github.com/epoberezkin/ajv#errorstextarrayobject-errors--object-options---string

like image 140
esp Avatar answered Sep 18 '25 08:09

esp