How to write a test to check if response does not contain specific value

Hi

I want to write some tests to check if the response does not contain a specific value or array or object.

Is it possible to test -ve scenario via postman scripts?

Thanks,
Abhijit

Hi @abhikulkarni.1988 ,

Welcome to the community :clap:

You can use Chai.js, sample use like below :+1:
More than examples are here -->

pm.test('is an Array', () => pm.expect(pm.response.json()).to.be.an('array').but.not.an('object'))

Thanks for your reply but I am trying to write a test like below but it is not working

pm.test(“Response not to have address”,()=>{
pm.expect(pm.response.text()).not.to.include(“address”);
});

Can you help to correct this?

pm.test("Response not to have address", function () 
{
    pm.expect(pm.response.text()).to.not.include("address");
});

You can use the as above, should be not.to.include instead of to.not.include :+1:

No luck with above solution

The answer you shared already contains the word address. Do you want to assert only for the word “address”? :thinking:

I see!

Word “address” is present in key “email_address” but my test is to check if key “address” is not present.

how to achieve this?

Hello @abhikulkarni.1988 , Welcome to the Community :wave:

So here you are testing that “address” shouldn’t be a part of your response body as a object?

In that case, you can try hasOwnProperty function.

var resp = JSON.parse(responseBody);
console.log(resp);
if (!resp.hasOwnProperty("address")){
pm.test("Address is not present", () => {
    console.log("Passed");
  });}
  else{
     console.log("Failed"); 
  }

Please try this :slightly_smiling_face: If this doesn’t work, kindly explain your need and share more details.

2 Likes

Thanks your solution worked!

But when the Address is present I want to report that the test failed.

I tried the below options in else block

pm.expect.fail(“Address is present”);

pm.test(“Address is present”, function () {
pm.expect(1).to.eql(2);
});

Is there better option than this?

@abhikulkarni.1988, May be you can try this:

pm.test("Address is not present", () => {
    if (!resp.hasOwnProperty("address")) {
        pm.expect(!resp.hasOwnProperty("address")).to.equal(true)
    }
    else {
        pm.expect.fail('Address is present')
    }
})

Hope this as per your request, I have modified and so you will get pass or fail in single test cases as you expected.

3 Likes

@bpricilla This worked :+1:

I am very thankful for the solution! :grinning:

1 Like

Glad to hear that :grinning: Happy to help always :+1: