简体   繁体   中英

Validating JS Tests against a JSON Schema

I have an API which returns response in the format

[
{"id": 12345,
"value": "some_string",
"practice_id": "12344"},

{"id": 12346,
"value": "some_other_string",
"practice_id": "12345"},
]

I am testing that the response validates a specific JSON-Schema, and my schema test is

response.body.should.have.schema({
        type: 'array',
        required: ['id', 'value', 'practice_id'],
        properties: {
            id: {
                type: 'number',
            },
            value: {
                type: 'string',
            },
            practice_id: {
                type: 'string',
                minLength: 5,
            }            
        }
    });

The issue is that the test passes even if I change the type of id to string or change the value of practice_id to number , which is not correct.

What am I doing wrong here? I am using Postman-BDD to validate the responses.

I guess your schema should be more like this:

{
  "type": "array",
  "items":
  {
    "required":
    [
        "id",
        "value",
        "practice_id"
    ],
    "properties":
    {
        "id":
        {
            "type": "number"
        },
        "value":
        {
            "type": "string"
        },
        "practice_id":
        {
            "type": "string",
            "minLength": 5
        }
    }
  }
}

You are missing the "items" keywords to actually define the content of the array. And this schema also gives an error in JSONBuddy on validating some sample data: 在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM