How to validate json schema using avj and postman

心不动则不痛 提交于 2021-02-15 07:00:58

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!