I want to exeucute Tests script in postman based on IF condition.
for eg:
var data = JSON.parse(responseBody);
if(responseCode.code === 404 ){
tests["TEst1: Invalid ID passed"];
}
When I use the above one it is not executing. How to use if condition on tests
To test the response code, you can do it directly.
tests["Status code is 400"] = responseCode.code === 400;
You have to use below line when you want to test the data inside the Json.
var data = JSON.parse(responseBody);
tests["Success --> Request & Response account first name matched"] = data.firstName === postman.getEnvironmentVariable("firstName");
Related
In pre-req script I wrote logic:
var obj = pm.request.body.toJSON();
var rawObj = JSON.parse(obj.raw);
var token =rawObj.token;
if(token==1){
pm.environment.set("status_code", 200);
pm.environment.set("msg", "token-1");
}else if(token==2){
pm.environment.set("status_code", 202);
pm.environment.set("msg", "token-2");
}
For response I wrote,
{"status_code":{{status_code}}, "msg":{{msg}}}
But in response the values are not passing, it prints above line as string.
How to send the environment value as response for mock server api request?
In order to save the response from postman API calls, I am executing Postman collection using newman run.
The collection runs when running using
newman run C:\TasteBud\NewMan\JSON-Order_collection.json --env-var unique_order_id=OD-06-07-I2Q5-JYRY5ARPN --environment C:\TasteBud\NewMan\EnvironmentJSON.json
However when I run the same collection as part of javascript or nodejs script.
node writeToFile.js
it throws error as node "1⠄ JSONError in test-script " refer attached image. I need to pass the auth token generated by login request to subsequent request. So I have variable assignment in the "test".
let response = pm.response.json();
pm.environment.set("auth_token", response.data.auth_token);
console.log(pm.response.json().data.auth_token);
Why cant I have "test" ? if no then how can I pass/set these environment variable for subsequent API call ?
Code inside writeToFile.js is here. writeToFile.js
Always use status code validation in your token generation. because every request is based on the token, if we receive negative status code, terminate the build.
postman.setNextRequest(null);
var jsonData = JSON.parse(responseBody);
if(responseCode.code === 200){
tests["Status code is 200"] = responseCode.code === 200;
postman.setEnvironmentVariable("AT", jsonData.oauth2.accessToken);
console.log("AccessToken : " +jsonData.oauth2.accessToken);
}
else{
postman.setNextRequest(null);
console.log("Error generating user token");
console.log("Status code : "+responseCode.code);
console.log("Status description : "+jsonData.statusDescr);
}
I am writing tests collections for endpoints and I want the test to check if the response param estadoAula has the same value as the request param estadoAula so I can test everything went as intended. The param need to be sent in the body and not in the URL
Request Body
{
"estadoAula": "1"
}
Response Body
{
"idAula": "8d4cf346-cda0-47ca-acae-33981738b4b6",
"estadoAula": "1"
}
Test
pm.test("Estado modificado correctamente",function(){
var data = pm.response.json();
let estadoAula = pm.request.body.estadoAula; <--- this doesn´t work, I need to get request param 'estadoAula'
pm.expect(data.estadoAula).to.eql(estadoAula);
});
You'll need to parse the request body, I am assuming you've set it to RAW along with 'JSON' as type.
This script should work for you:
pm.test("Estado modificado correctamente",function(){
let data = pm.response.json(),
requestBody = JSON.parse(pm.request.body.raw);
pm.expect(data.estadoAula).to.eql(requestBody.estadoAula);
});
From below Response, I want to fetch the value of "responseCode" and store temporarily. If a value is 1 then on Console, I want to write "Test PASS". Can anyone share code for this test?
{
"data":{
"transactionId":"$1"
},
"responseMessage":"Transaction successfully done. Transaction Id : txn_15594028419901124218",
"responseCode":1
}
I tried to use the following code to set the variable:
var jsonData = JSON.parse(responseBody);
pm.globals.set("responseCode",jsonData.data.responseCode);
This basic test would check that value in the response, store the variable and also write Test PASS to the console
pm.test("Check the Response Code is 1", () => {
pm.expect(pm.response.json().responseCode).to.eql(1);
pm.globals.set("responseCode", pm.response.json().responseCode)
console.log("Test PASS")
});
This doesn't account for the test failing and writing Test FAIL to the console, you kind of get that anyway in the Postman UI.
If you didn't want to wrap this in a test, you could just do something like:
if(pm.response.json().responseCode === 1){
pm.globals.set("responseCode", pm.response.json().responseCode)
console.log("Test PASS")
}
else {
console.log("Test FAIL")
}
When using Postman I validate the JSON response like so:
tv4.addSchema(globalSchema);
const valResult = tv4.validate(data, schema);
// schema is an object, which is a subschema from the larger globalSchema
which works fine, except for the error reporting. The error object I get is missing dataPath and schemaPath, making it hard for my user to find out where the actual problem is. Is there a way to get those properties? (tried validateResult and validateMultiple to no avail)
As an alternative I tried ajv, but as I am in draft-04, it gives me errors. The advice from their site
var ajv = new Ajv({schemaId: 'id'});
// If you want to use both draft-04 and draft-06/07 schemas:
// var ajv = new Ajv({schemaId: 'auto'});
ajv.addMetaSchema(require('ajv/lib/refs/json-schema-draft-04.json'));
does not work because the Postman sandbox does not allow me to require that… any thoughts?
See also: https://community.getpostman.com/t/json-schema-validation-troubles/5024
Here's how I validate schema's with postman to get more detailed errors:
const schema = {
};
var jsonData = JSON.parse(responseBody);
pm.test('Checking Response Against Schema Validation', function() {
var result=tv4.validateMultiple(jsonData, schema);
console.log(result);
pm.expect(result.valid).to.be.true;
});