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