Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
333 views
in Technique[技术] by (71.8m points)

ajv - How to validate json schema using avj and postman

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

enter image description here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...