Pixi Dixi
Pixi Dixi

Reputation: 123

Problem with schema validation using Postman

Body of my req:

[
  {
    "postId": 1,
    "id": 1,
    "name": "name abc",
    "email": "[email protected]",
    "body": "something"
  },
...
]

I am trying to validate it like below:

var schema = {
  "type": "array",
  "properties": {
    "postId": {
      "type": "integer"
    },
    "id": {
      "type": "integer"
    },
     "name": {
      "type": "string"
    },
    "email": {
      "type": "string",
      "pattern": "^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$"
    },
    "body": {
      "type": "string"
    }
  },
  "required": [
    "postId",
    "id",
    "name",
    "email",
    "body"
  ]
};

pm.test('Schemat jest poprawny', function() {
  pm.expect(tv4.validate(jsonData, schema)).to.be.true;
});

The test is ok even if I change for example id type for string or email pattern for invalid one.

What is wrong with that code?

Upvotes: 2

Views: 591

Answers (1)

Danny Dainton
Danny Dainton

Reputation: 25921

I would recommend moving away from tv4 for schema validations and use the built-in jsonSchema function, as this uses AJV.

Apart from that, your schema didn't look right and was missing the validation against the object, it looks like it was doing it against the array.

This might help you out:

let schema = {
    "type": "array",
    "items": {
        "type": "object",
        "required": [
            "postId",
            "id",
            "name",
            "email",
            "body"
        ],
        "properties": {
            "postId": {
                "type": "integer"
            },
            "id": {
                "type": "integer"
            },
            "name": {
                "type": "string"
            },
            "email": {
                "type": "string",
                "pattern": "^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$"
            },
            "body": {
                "type": "string"
            }
        }
    }
}

pm.test("Schemat jest poprawny", () => {
    pm.response.to.have.jsonSchema(schema)
})

Upvotes: 1

Related Questions