问题
I'm trying to validate the following json that looks like this:
{
"errors": false,
}
using this on postman:
var Ajv = require('ajv'),
ajv = new Ajv({logger: console, coerceTypes: false}),
schema = {
"errors": {
"type": "number"
}
};
pm.test('Schema is valid', function() {
var error = pm.response.json()['errors'];
console.log("this is error: " +error);
pm.expect(ajv.validate(schema, {errors: error})).to.be.true;
});
pm.test('Schema is valid different way', function() {
var error = pm.response.json()['errors'];
console.log("this is error: " +error);
var validate = ajv.compile(schema);
pm.expect(validate(pm.response.json())).to.be.true;
});
but it's always passing, even though my errors object is a boolean
and not a number
. What am I doing wrong?
note: the logs look like this
this is error: false
回答1:
You can check json schema using avj in Postman as follows:
var Ajv = require('ajv'),
ajv = new Ajv({logger: console}),
schema = {
"properties": {
"errors": {
"type": "boolean"
}
}
};
pm.test('Schema is valid', function() {
var error = pm.response.json()['errors'];
pm.expect(ajv.validate(schema, {errors: error})).to.be.true;
});
Data:
{
"errors": false
}
Result: Pass
Data:
{
"errors": true
}
Result: Pass
Data:
{
"errors": 123
}
Result: Fail
An alternate way
pm.test('Schema is valid', function() {
pm.expect(typeof(pm.response.json().errors) === "boolean").to.be.true;
});
来源:https://stackoverflow.com/questions/55021811/how-to-validate-json-schema-using-avj-and-postman