We got the following array containing books as objects:
[
{
"id": 1,
"name": "True Love",
"type": "non-fiction",
"available": false
}
{
"id": 5,
"name": "Real Trouble",
"type": "fiction",
"available": true
}
{
"id": 8,
"name": "CSI Miami",
"type": "fiction",
"available": true
}
]
Here is the initial Postman test script:
const response = pm.response.json();
const fictionBooks = response.filter((book) => book.available === true);
console.log(fictionBooks[0]);
In the console.log we have hardcoded by using [0] that we want our result to be the first object in the array meeting the criteria in the fictionBooks variable. The filter() function will drop out all books that are not available.
Let’s create assignments to test if the item we are looking for is an object, fiction and available
const response = pm.response.json();
const fictionBooks = response.filter((book) => book.available === true);
const book = fictionBooks[0];
pm.test("Book found" () => {
pm.expect(book).to.be.an('object'); //We expect that the book is an object
pm.expect(book.type)to.eql("fiction");
pm.expect(book.available).to.eql(true);
});
First, we have transformed the previously used console.log to a variable that we can reuse.
After that, we have updated it with a test with a few assertions.
NOTE:
Following assertion we could actually write in other way as well:
pm.expect(book.available).to.eql(true); //Previously used
pm.expect(book.available).to.be.true; //Meaning the same