3

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?

pedalpete
  • 21,076
  • 45
  • 128
  • 239

1 Answers1

9

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

esp
  • 7,314
  • 6
  • 49
  • 79
  • Thanks, the main documentation says `if (!valid) console.log(ajv.errorsText());` so I was going with that. – pedalpete Aug 14 '17 at 08:35
  • yes, in the case where it uses ajv.validate. Need to add errorsText to the previous example. – esp Aug 14 '17 at 08:38