How do I write test for same request with different body?

If I have a request how can I write specific tests for different sets of data.
For example,

if I have a body:

{
    "name": "Test"
    "email": "test@test.com"
}

I want to run a certain test case againt this particular request, say:

pm.test("response should be 200 when email is provided",  function() {
    pm.response.to.have.status(200);
});

Now if I have a body for the same request without an email:

{
    "name": "Test"
}

I want to run only this test case againt this particular request body:

pm.test("response should be 400 when email is not provided",  function() {
    pm.response.to.have.status(400);
});

All of this should happen in the same request, when the Send is pressed. How to achieve this?

Hi @leen, you can write tests conditionally.

This is just an example to do so:

let resp = {};

// This is because if you try to do `JSON.parse` on a response
// which is not a JSON then it'll throw an error
try {
    resp = pm.response.json();
}
catch (e) {}

pm.test(`response code should be ${pm.response.code} based on email availability`, function () {
  if (_.get(resp, 'email')) { // Using lodash which is built-in postman
    pm.response.to.have.status(200);
  }
  else {
    pm.response.to.have.status(404);
  }
});

There can be multiple ways to do things like these, based on what you’re checking.
But yes, you can use the entire power of javascript to do things like these.

I also used lodash which is built-into postman.
There are multiple other libraries that are built-in with postman and you can use them in the pre-request / test scripts.

3 Likes

Hi @leen

Was looking for an answer myself->

What you could do is set the expected status code as Environment variable, and have the prerequest script fill it with the expected value according to how your request looks: IE

This is almost the same code as @singhsivcan suggested but then using the request instead of the response.

var req = JSON.parse(pm.request.body.raw);

if (_.get(req, 'email')) {
    pm.environment.set("expectedstatus", (200));
} else {

pm.environment.set("expectedstatus", (400));
}

then have your test check the response status against (pm.environment.get(“expectedstatus”));