如何在Postman测试脚本中的系统响应中包含2个元素的数组中存储值

时间:2017-09-05 05:13:23

标签: javascript postman

我正在尝试使用以下代码将"TokenType": "UserAccount"的令牌存储到变量中,但它似乎无法正常工作。请帮助。

我的代码:

if (responseCode.code === 200) {
    try {
        var tokenValue = JSON.parse(responseBody);
    } catch (e) {
        if (e) {
            console.log(e);
        }
    }
}
postman.setGlobalVariable("Acc_Token", tokenValue[0].value);

由标记值组成的数组:

"value": [
    {
        "Expires": "2017-09-05T05:07:11.0778675Z",
        "IsRefreshable": false,
        "Token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzUxMiJ9.eyJhdWQiOiJodHRwOi8vcWEubWFzc2l2ZWF4aXMuY29tL0lTTC9BcGkvVjEvRGF0YXNlcnZpY2UiLCJzdWIiOiJTZXR0aW5ncyIsImV4cCI6MTUwNDU4ODAzMSwidXNlckFjY291bnRJZCI6Ijg5MjRkMzFkLWFhYjktNDkzYy05N2NlLWRkMTc5NzQyNGE3ZSIsInVzZXJQcm9maWxlSWQiOiIyY2YyZWEyNC01NTRmLTQzYzktYjA1NS1hMjM2NGVjYWY0ZjkiLCJlbWFpbCI6ImFwYXJuYTExNEBtYXNzaXZlLmNvbS5hdSIsImRldmljZSI6IndlYl9icm93c2VyIiwidmFsaWRVbnRpbCI6MTUzNjEyMzQzMSwic3Vic2NyaXB0aW9uIjoiUmVnaXN0ZXJlZCJ9.J7CT2nCrnNOxQI4kHyyIVt4ASfd6dl_ZNnAO5azZ5p49w3fa-B2FTGYmiC8A8S4aACt6g4MGKjqfEn8X7vBofxEnL9DcfSDK4ZTqZ2J-XTVGSVafAp6YU05DMlpUFYNdDjx8b2eRJhvCH2NR3zaD68fiemezbYBzxw_J35i01tOL6H8odSgvhxwAKfONWhH04_nm2P1PUue0EKtcdvz7FAKcwpF9EOjxCXVMwmfQOH8C2FD91s94_p-q4l0MW3Y2Vonlw-q2nzK5ZN17F38wQOyvnjGeeQFBxa1bYkj3h3qnhy1Z80Ka6Gcpk5dbEbfYT5DU4zqXM4uIZHQzzivo2g",
        "TokenType": "UserAccount"
    },
    {
        "Expires": "2017-09-05T05:07:11.0828684Z",
        "IsRefreshable": false,
        "Token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzUxMiJ9.eyJhdWQiOiJodHRwOi8vcWEubWFzc2l2ZWF4aXMuY29tL0lTTC9BcGkvVjEvRGF0YXNlcnZpY2UiLCJzdWIiOiJTZXR0aW5ncyIsImV4cCI6MTUwNDU4ODAzMSwidXNlckFjY291bnRJZCI6Ijg5MjRkMzFkLWFhYjktNDkzYy05N2NlLWRkMTc5NzQyNGE3ZSIsImRlZmF1bHRVc2VyUHJvZmlsZUlkIjoiMmNmMmVhMjQtNTU0Zi00M2M5LWIwNTUtYTIzNjRlY2FmNGY5IiwidXNlclByb2ZpbGVJZCI6IjJjZjJlYTI0LTU1NGYtNDNjOS1iMDU1LWEyMzY0ZWNhZjRmOSIsImVtYWlsIjoiYXBhcm5hMTE0QG1hc3NpdmUuY29tLmF1IiwiZmlyc3RMb2dpbkRhdGUiOjE1MDQ1ODYxNjcsImxhc3RMb2dpbkRhdGUiOjE1MDQ1ODc0MTEsInNlc3Npb25EYXRlIjoxNTA0NTg3NDMxLCJzZXNzaW9uQ291bnQiOjcsImRldmljZSI6IndlYl9icm93c2VyIn0.JoaEijd6baSsHiVofeP3jUowJxp91SDcFb4zANj_ZnR0gHpp2yqCBQD4zh22maB7Yp4m5TD8jkfOuj9id2TD0N6pCa8Y9fXNQGAnZy963XrwnRz14AEfg954AGeAHSw6_qQGxh-xlc63rlsn62gnmZ0yPZZDHHbjYngJKsr8Kv_5qBNjZ9TX2y8H0PAm_STkw5PXqaCjtfMFPVyGFvDpVzx2wj1mMwnAS7V6Ftnr1-flaIjRmGXv0XQiND-uzxEZa8wjfLOEbayNS1IgbBRuiixaOKUvul14FwxasdojnZ5UOB5R_I4OUzp6WjWTax2rjbvIXxdlj0iyLeL7WD6egQ",
        "TokenType": "UserProfile"
    }
]

错误:

  

评估测试脚本时出错:TypeError:无法读取属性' value'未定义的

1 个答案:

答案 0 :(得分:0)

您的value财产不在第一项中。它在对象本身

通过tokenValue.value[0]访问将为您提供"TokenType": "UserAccount"的对象。

并将postman.setGlobalVariable移到if语句中。