Postman测试脚本报错:TypeError: 无法读取undefined的accountNumber属性
问题:Postman测试脚本无法找到指定accountId的账户并报错
API返回的JSON示例(实际共35749条数据):
{ "searchTotalMatch": 35749, "searchItems": [ { "accountId": 1, "accountNumber": "32520A22DF0X", "accountName": "3M Company" }, { "accountId": 2, "accountNumber": "43371C22DF0X", "accountName": "Risk Managed Insurance Consortiu" } ] }
编写的测试脚本:
var responseData = pm.response.json().searchItems; var test_account = responseData.find((item) => item.accountId === "100"); pm.collectionVariables.set('TESTACCOUNT', test_account.accountNumber);
收到的错误信息:
Couldn't evaluate the test script:
TypeError: Cannot read properties of undefined (reading 'accountNumber')
问题分析与解决
错误原因
- 类型不匹配:JSON返回的
accountId是数字类型(如1、2),但脚本中用字符串"100"做全等比较(===),导致find方法找不到匹配项,返回undefined。后续访问undefined.accountNumber自然抛出错误。 - 未处理空值情况:即使匹配逻辑正确,若目标
accountId不存在,test_account仍会是undefined,直接访问其属性会触发报错。
修正后的脚本
var responseData = pm.response.json().searchItems; // 用数字100匹配,与JSON中的accountId类型保持一致 var test_account = responseData.find((item) => item.accountId === 100); // 先判断是否找到数据,再执行变量设置 if (test_account) { // 需求是保存accountName,这里修正了原脚本的accountNumber字段 pm.collectionVariables.set('TESTACCOUNT', test_account.accountName); } else { console.log('未找到accountId为100的账户'); // 可设置默认值或其他处理逻辑 pm.collectionVariables.set('TESTACCOUNT', ''); }
关键说明
- 确保类型一致:用数字
100而非字符串"100"进行比较,全等运算符===会同时检查值和类型。 - 增加空值判断:避免因找不到数据导致的脚本崩溃,同时可在控制台输出提示信息。
- 字段修正:原需求是保存
accountName,原脚本误写为accountNumber,已同步修正,若实际需要accountNumber可自行改回。
内容的提问来源于stack exchange,提问作者EricaX
相关产品推荐
相关产品推荐

