and the response from API is:
{
“fact”: “Cats are North America’s most popular pets: there are 73 million cats compared to 63 million dogs. Over 30% of households in North America own a cat.”,
“length”: 149
}
Now what is need is validate that in the const schema, there have to be a key named “fact” and “length” and it have to be appear in the correct order in the API response. But what I get is, whatever I change in schema, as long as it have in the response, my test will passed.
What I mean is, the code I wrote should be failed but it not and the correct that I want is:
JSON itself does not guarantee the order of properties in an object as it is considered an unordered key-value pair, so JSON Schema by extension does not validate if a certain key comes before another. You will have to do this check manually, and there are a couple of ways you could achieve it in JavaScript.
One way is to use Object.keys(obj) to extract the keys as an array and iteratively validate the position of each key against a Northstar array of keys. See example below.
const json = {
"fact": "Cats are North America’s most popular pets: there are 73 million cats compared to 63 million dogs. Over 30% of households in North America own a cat.",
"length": 149
};
const expectedOrder = ["fact", "length"];
const actualOrder = Object.keys(json);
const isValidOrder = expectedOrder.every((key, index) => actualOrder[index] === key);
console.log(isValidOrder ? "The order is correct." : "The order is incorrect.");