Reputation: 53
I want to integrate Postman/ Newman API tests into CICD, so the test results should always be passed (or skipped). Therefor I want to use conditional tests, dependent on the data of the response.
I tried the method described on GitHub, but the condition in my case is very different.
So if the json body of the response contains an empty array, tests should be skipped. If not, perform tests...
Empty data
{
"data": []
}
Testable data
{
"data": [
{
"key1": "value1",
"key2": {
"amount": 1357,
"unit": "units"
},
"from": "2019-08-01",
"to": "2019-08-31",
}
]
}
Test script
let response = JSON.parse(responseBody);
pm.test("Status code is 200", function() {
pm.expect(pm.response.code).to.equal(200);
});
(pm.expect(pm.response.json().data).to.be.empty === true ? pm.test.skip : pm.test)('Body is empty', function () {
pm.environment.set("key2Amount", response.data[0].key2.amount);
var key2Amount = pm.environment.get("key2Amount");
pm.test("Response includes corresponding amount", function () {
pm.expect(pm.response.json().data[0].key2.amount).to.eql(key2Amount);
});
});
Empty data: TypeError: Cannot read property 'key2' of undefined
.
Testable data: AssertionError: expected [ Array(1) ] to be empty
.
I've also tried it with
(pm.expect([]).to.be.an('array').that.is.empty ? pm.test : pm.test.skip)
Testable data: Tests performed positive.
Empty data: TypeError: Cannot read property 'key2' of undefined
. Why not skipped?
Further
(pm.expect([]).to.be.empty ? pm.test.skip : pm.test)
Empty data: skipped tests
Testable data: skipped tests
What would be the correct condition on the array to make the tests run or skipped?
Upvotes: 5
Views: 11742
Reputation: 25881
Could you use something like this:
let response = pm.response.json();
pm.test("Status code is 200", function() {
pm.expect(pm.response.code).to.equal(200);
});
let skipTest = (response.data === undefined || response.data.length === 0);
(skipTest ? pm.test.skip : pm.test)('Body is empty', function () {
pm.environment.set("key2Amount", response.data[0].key2.amount);
pm.test("Response includes corresponding amount", function () {
pm.expect(response.data[0].key2.amount).to.eql(pm.environment.get("key2Amount"));
});
});
Upvotes: 2