繁体   English   中英

如何将全局变量传递给JSON object 在Javascript中进行校验

[英]How to pass global variables to JSON object for validation in Javascript

您好,我现在转到 javascript 并在 Postman 中编写用于 API 测试的脚本以自动化我的用例。 需要以下查询的帮助。

假设我有如下 API 请求。

API request: https://reqres.in/api/users/2

回复:

{
   "data":{
      "id":2,
      "email":"janet.weaver@reqres.in",
      "first_name":"Janet",
      "last_name":"Weaver",
      "avatar":"https://reqres.in/img/faces/2-image.jpg"
   },
   "support":{
      "url":"https://reqres.in/#support-heading",
      "text":"To keep ReqRes free, contributions towards server costs are appreciated!"
   }
}

查询来自响应,如果 data.id == 2 那么我必须从 postman 的全局变量中读取“电子邮件”和“头像”键并开始验证。

代码:

const response = JSON.parse(responseBody);
if (response.data.id === 2) {
//Here i have to read the 'email' & 'avatar' keys from global variables of postman.
tried response.data.pm.globals.get('email') & response.data.pm.globals.get('avatar') but its failing as the calling itself is not proper i belive.
}

请帮助并提前致谢。

Tests部分使用此代码

const response = JSON.parse(responseBody);

if (response.data.id === 2) {
    pm.globals.set("email", response.data.email);
    pm.globals.set("avatar", response.data.avatar);
    console.log(pm.globals.get("email"))
    console.log(pm.globals.get("avatar"))
}

你可以在控制台看到它的结果。

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM