skip to Main Content

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


  1. I see that you are converting your api response into json using below code –

    var responseData = pm.response.json().searchItems;
    

    Please note that json() method is asynchronous and you would need to either use await or then() to get the final value.

    So, you can add await in above mentioned code and make the following changes –

    var responseData = await pm.response.json(); // don't forget to add async to the wrapper method
    var searchItems = responseData.searchItems;
    

    Also, replace "100" with 100 in below code –

    var test_account = responseData.find((item) => item.accountId === "100");
    
    Login or Signup to reply.
  2. You could do the following:

    • Change 100 to "100" (Use number instead of string)
    • Change strict equals to equals ( == instead of ===)

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search