1

Pre Request:

//Create random number
let randomNum = 
        Math.floor((1 + Math.random()) * 0x10000)
            .toString(16)
            .substring(1);

//Set Random # as the Random ID       
pm.environment.set("randomNum", randomNum);

Body:

{   
    "AccountNumber": "AA{{randomNum}}",
            "Name": "AA {{randomNum}}",
            "Reference": "AA 01",
            "VatCodeId": 1,
              "UserCreated": "James"
}

Response:

{
    "Id": 18,
    "AccountNumber": "AA7e40",
    "Name": "AA 7e40",
    "Reference": "AA 01",
    "VatCodeId": 1,
    "DateCreated": "2022-01-27T09:53:43.6734454+00:00",
    "UserCreated": "James"
}

Note: The Id field is being created when a 200 response is being returned, this is unique to the DB and increments by 1 for every new account created.

I am trying to extract the Id and use that as a Enviroment variable so it can be chained (for deletion of accounts). The Test script is:

var accountUniqueId = JSON.parse(responseBody);
pm.environment.set("accountId", json.result.data.Id);

Though I have tried variations of it such as:

var accountUniqueId = pm.response.json();
pm.environment.set("accountId", jsonData.Id);
var accountUniqueId = pm.response.json();
pm.environment.set("accountId", jsonData.response.Id);

The response in the Test is showing as: There was an error in evaluating the test script: ReferenceError: json is not defined

The Enviroment Variable is being created with a current value of: [object Object].

Jimmy
  • 85
  • 1
  • 11
  • 2
    You were assigning the full response to a variable `accountUniqueId` but then not using that and using `jsonData.Id` instead. `accountUniqueId.Id` would have worked. – Danny Dainton Jan 27 '22 at 10:52

1 Answers1

3

This should do it:

let jsonData= pm.response.json();
pm.environment.set("accountId", jsonData.Id);
Christian Baumann
  • 3,188
  • 3
  • 20
  • 37
  • 1
    Thanks very much Christian. I should remove the response in the enviroment set for future test. var accountUniqueId = pm.response.json(); pm.environment.set("accountId", jsonData.response.Id); – Jimmy Jan 27 '22 at 10:51
  • 1
    Or just that > `pm.environment.set("accountId", pm.response.json().Id);` :D – Danny Dainton Jan 27 '22 at 10:57