【问题标题】:Can not check the JSON value from the response body无法从响应正文中检查 JSON 值
【发布时间】:2021-10-16 22:45:08
【问题描述】:

我刚开始使用邮递员测试 api。我遇到了一个关于 json 路径的问题..

在 json 文件中我有如下代码


{
 "users": [
   {
     "firstName": "UserOne",
     "lastName": "One",
     "subjectId": 1,
     "id": 1
   },
   {
     "firstName": "UserTwo",
     "lastName": "Two",
     "subjectId": 2,
     "id": 2
   },
   {
     "firstName": "UserThree",
     "lastName": "Three",
     "subjectId": 3,
     "id": 3
   }
 ],
 "subjects": [
   {
     "id": 1,
     "name": "SubOne"
   },
   {
     "id": 2,
     "name": "SubTwo"
   },
   {
     "id": 3,
     "name": "SubThree"
   }
 ]
}

我用json-server --watch db.json启动json服务器

之后我使用邮递员发送 GET 请求 请求网址http://localhost:3000/users

这是我得到的身体

[
    {
        "firstName": "UserOne",
        "lastName": "One",
        "subjectId": 1,
        "id": 1
    },
    {
        "firstName": "UserTwo",
        "lastName": "Two",
        "subjectId": 2,
        "id": 2
    },
    {
        "firstName": "UserThree",
        "lastName": "Three",
        "subjectId": 3,
        "id": 3
    }
]

我试图使用下面的 sn-p 代码验证 id 1 中的名字

pm.test("Your test name", function () {
    var jsonData = pm.response.json();
    pm.expect(jsonData.users[0].firstName).to.eql('UserOne');
});

但输出是 FAIL Your test name | TypeError: Cannot read property '0' of undefined

我在这里需要帮助,因为 json 路径 users[0].firstName 应该给我第一个索引..

【问题讨论】:

  • 您是否尝试过记录 jsonData 以查看用户数组是否存在于您的响应中?
  • var jsonData = JSON.parse(responseBody); console.log(jsonData.users); 输出undefined

标签: postman postman-testcase


【解决方案1】:

您的回复中没有密钥users,因此当您尝试访问不存在的密钥时,您将收到错误Cannot read property 'xxx' of undefined。要解决这个问题,您只需要:

pm.test("Your test name", function () {
    var jsonData = pm.response.json();
    pm.expect(jsonData[0].firstName).to.eql('UserOne');
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-05
    • 2021-11-26
    • 2020-09-21
    • 1970-01-01
    • 1970-01-01
    • 2015-08-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多