Reputation: 155
I'm trying to understand how to write an assertion in postman that will verify there are no additional key:value pairs in an object.
For example, here is some test data:
"testArray": [
{
"key-1" : "value1a"
"key-2" : "value2a"
},
{
"key-1" : "value1b"
"key-2" : "value2b"
},
]
I can easily write an assertion to very that testArray has a length of '2', i can verify the actual values of the key value pairs are returning as expected. I'm having a problem figuring out how to figure out that a key-3 was NOT returned.
Now, if I know what a possible key is, i can verify it comes in as 'undefined', but if I don't know the name of a potential key value pair I want to make sure that i can assert these are ONLY the options I want.
If there isn't a simple solution such as being able to count the number of key:value pairs in an object, would I need to go down the route of creating a loop to iterate through the objects in the array to compare them to a valid values list?
Upvotes: 1
Views: 2079
Reputation: 19929
HI this should be done using Json schema and not using for loop
Refer below answer:
https://stackoverflow.com/a/58436108/6793637
You can generate schema by just copy pasting your response in
Make sure you select the checkbox before creating schema
Upvotes: 1
Reputation: 25851
I'm not sure what tests/assertions you have in place at the moment but you could extend those to add this:
pm.test("Each object should have 2 keys", () => {
_.each(pm.response.json().testArray, (item) => {
pm.expect(item).to.be.an('object').and.have.keys(['key-1', 'key-2'])
})
})
This is just an example based on the data you included, your data doesn't look like an actual response because it's not valid JSON but I modified it my end to see the test passing/failing.
This assertion would check that each item in the testArray
array is an object and it has only the keys that should be there. If you were to add a 3rd key to your data, the assertion would fail.
Upvotes: 1