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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With