简体   繁体   中英

How can I check request body has a key or not in postman tests

I'm trying to write postman tests. I want to check response according to request so I want to know what requestBody has. requestbody is a json like

{"subscription":{"supi":"value","gpsi":"value","pei":"value"}}. 

This 3 elements(supi,gpsi,pei) is optional so I want to check which one exist in requestBody. I can access supi's value if it is exist with below code.

requestBody = JSON.parse(pm.request.body); var subscription= requestBody.subscription; var supi=subscription.supi;

I try to control if supi exists or not with if(subscription.supi !== null) . As I understand when supi is not in requestBody, subscription.supi does not return null so my if check doesnt work properly. How can I control supi is exist or not in requestBody?

In javascript if a object property is not present it will return undefined

so use

   if(subscription.supi !== undefined).

Or you can also use

  Object.keys(subscription).includes(supi)

This will extract all keys and check it has the key supi

You can also use

 subscription.hasOwnProperty('supi')

This will check the subscription has the property supi and this is the best way

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM