Search code examples
testingautomated-testspostman

How to set Postman tests with if else?


I want to have a json-schema validation test in Postman for both cases - positive and negative response. There is my test in Postman.

positiveSchema = {there is a json-schema for positive response}

negativeSchema= {there is a json-schema for negative response}

if (pm.response.to.be.success) {
   pm.test("Positive response", function () {
    pm.response.to.have.jsonSchema(positiveSchema);
});

    } else {

 pm.test("Negative response", function () {
    pm.response.to.have.jsonSchema(negativeSchema);
});
    }

So, as I think it should work: if the response code is 2XX test checks the positive json-schema validation. If the response code is not 2XX test checks the negative json-schema validation.

But I've got an error

There was an error in evaluating the test script: AssertionError: expected response code to be 2XX but found 500

What is wrong with my test?

Different patterns - if (pm.response.to.be.success) else if (pm.response.to.be.error).

Tiny validator doesn't work. But it's ok for my Postman version.

pm.test('Schema is valid', function () {
    pm.expect(tv4.validate(pm.response, negativeSchema)).to.be.true;
});

If I don't use "if else" - tests work. But I've got 1 passed and 1 failed tests. I don't want to use such case.


Solution

  • The problem is pm.response.to.be.success doesn't return boolean value, it's a test itself, therefore it throws error when a assertion fails.

    To fix that, you can change if statement to

    if (pm.response.code === 200) {
       ...
    }
    

    if you want the response code belongs 2xx, then you can change the condition is something like that.

    if (200 <= pm.response.code &&  pm.response.code <= 299) {
       ...
    }