I’m new to Javascript and JSON and wondering if anyone could help with this error. My GET API returns the JSON file below (it returns 35749 items so for simplicity I just showed 2 of them here)
{
"searchTotalMatch": 35749,
"searchItems": [
{
"accountId": 1,
"accountNumber": "32520A22DF0X",
"accountName": "3M Company",
},
{
"accountId": 2,
"accountNumber": "43371C22DF0X",
"accountName": "Risk Managed Insurance Consortiu",
}
]
}
I want to find the accountName of the account that thas accountId as 100 and save it to a collection variable(TESTACCOUNT), and I wrote the test script below:
var responseData = pm.response.json().searchItems;
var test_account = responseData.find((item) => item.accountId === "100");
pm.collectionVariables.set('TESTACCOUNT', test_account.accountNumber);
I got the error message of
Couldn’t evaluate the test script:
TypeError: Cannot read properties of undefined (reading ‘accountNumber’)
Does this mean it didn’t filter out the item at all? What is wrong with the script? Thanks a lot!
2
Answers
I see that you are converting your api response into json using below code –
Please note that json() method is asynchronous and you would need to either use
await
orthen()
to get the final value.So, you can add
await
in above mentioned code and make the following changes –Also, replace "100" with 100 in below code –
You could do the following:
You can also avoid errors, by using a conditional membership operator
test_account ?. accountNumber instead of test_account . accountNumber
But note that, this will store undefined if your test_account is undefined, it avoids the error by looking for the member accountNumber if and only if test_account exists.