My question: I have an array with some element and I want to pass the test case if the element is not present in the array. And I also want to pass the test case if the array is not present in the output.
For example: The response body is as below:
{
“Fruits”: [“Mango”]
}
I want the test to be pass if anything other than “Mango” is present in the array or it should also pass if the array “Fruits” don’t exists.
pm.test("Check fruits", function () {
var jsonData = pm.response.json();
if(jsonData.hasOwnProperty("Fruits")) {
pm.expect(jsonData.Fruits).to.not.include("Mango");
}
});
To explain what is happening here:
The hasOwnProperty check is looking to see whether Fruits is present in the input. (If it is not present, it will not attempt the assertion, so the test will automatically pass.)
The assertion uses a chai assertion to check that “Mango” is not present in the array. It will pass if there are 0 array elements, or if none of the elements are called “Mango”.
I hope this helps, please ask if you have any further questions!
Still I was not able to pass the test case if the response does not have “Fruits”? Suppose it return some other array. And in this case how will I pass the above test?
Basically, I want the above functionality to check the errors in the response. If one error shows up in form of array (that particular test should fail) and, I want other test cases to be pass which have other errors in the tests.
I hope you understand the question. Once again thank you for helping:)
I’m not sure I understand in which scenario this is not working for you. Here are a few examples that you could try in the Tests tab (I have included inline json rather than reading from response); could you possibly add another data sample which is not working for you?
pm.test("Should pass if nothing in the response", function () {
var response = {};
if(response.hasOwnProperty("Fruits")) {
pm.expect(response.Fruits).to.not.include("Mango");
}
});
pm.test("Should pass if Fruits present but not Mango", function () {
var response = {"Fruits": ["Banana", "Apple"]};
if(response.hasOwnProperty("Fruits")) {
pm.expect(response.Fruits).to.not.include("Mango");
}
});
pm.test("Should pass if Fruits not in the response", function () {
var response = {"Vegetables": ["Carrot"]};
if(response.hasOwnProperty("Fruits")) {
pm.expect(response.Fruits).to.not.include("Mango");
}
});
pm.test("Fails if Fruits contains Mango", function () {
var response = {"Fruits": ["Apple", "Mango"]};
if(response.hasOwnProperty("Fruits")) {
pm.expect(response.Fruits).to.not.include("Mango");
}
});