【问题标题】:Check response header's value in Postman tests在 Postman 测试中检查响应标头的值
【发布时间】:2018-08-21 12:43:52
【问题描述】:

我想检查具体响应标头(“位置”)中的值作为 Postman 中的测试结果。 在邮递员的文档中,我找到了如何使用

检查标题是否存在的示例
pm.test("Content-Type is present", function () {
   pm.response.to.have.header("Content-Type");
});

但我正在寻找类似的东西

pm.test("Location value is correct", function () {
   CODE HERE THAT CHECKS "Location" HEADER EQUALS TO SOMETHING;
});

【问题讨论】:

    标签: testing automated-tests postman


    【解决方案1】:

    我终于找到了解决办法:

    pm.test("Redirect location is correct", function () {
       pm.response.to.have.header("Location");
       pm.response.to.be.header("Location", "http://example.com/expected-redirect-url");
    });
    

    【讨论】:

    • 沙盒你很厉害!
    • 你是沙盒! :)
    • 使用 Postman v7.35.0,记得在设置中关闭 自动跟随重定向 以查看重定向响应。
    【解决方案2】:

    这是在测试部分中获取特定响应标头的另一种方法...

    loc = pm.response.headers.get("Location");

    以防万一,如果后续请求需要特定信息,例如标头值,那么您也可以将其存储/设置为环境变量,如下所示,并进一步重复使用

    pm.environment.set("redirURL", loc);

    var loc = null;
    pm.test("Collect redirect location", function () {
       pm.response.to.have.header("Location");
       loc = pm.response.headers.get("Location");
       if (loc !== undefined) {
          pm.environment.set("redirURL", loc);
       }
    });
    

    优点是——变量中收集的值可以被操纵。

    但这一切都取决于情况。例如,您可能想要提取和预处理/后处理重定向 URL。

    例如,

    在运行测试集合时,您希望收集变量中的值并将其更改为指向模拟服务器的 host:port

    【讨论】:

      【解决方案3】:

      HeadersListhas(item, valueopt) → {Boolean} 方法,所以检查标题的最简单方法是:

      const base_url = pm.variables.get("base_url")
      
      pm.test("Redirect to OAuth2 endpoint", () => {
          pm.expect(pm.response.headers.has("Location",`${base_url}/oauth2/`)).is.true
      })
      

      【讨论】:

        【解决方案4】:

        pm.test("Location value is correct", function () {
           pm.expect(pm.response.headers.get('Location')).to.eql('http://google.com');
        });

        【讨论】:

          【解决方案5】:

          Postman 也支持 ES6/ES2015 语法,允许我们使用箭头函数。

          下面是一个简单的测试来验证公共响应标头是否存在:

          pm.test("Verify response headers are present ", () => {
              pm.response.to.have.header("Date");
              pm.response.to.have.header("Content-Length");
              pm.response.to.have.header("Content-Type");
          });
          

          当然,您可以检查您的 API 返回的任何自定义标头。

          【讨论】:

            【解决方案6】:

            使用BDD 期望/应该样式:

            pm.test("Redirect location is correct", () => {
               pm.expect(pm.response).to.include.header("Location");
               pm.expect(pm.response).to.have.header("Location", "http://example.com/expected-redirect-url");
            });
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2018-09-10
              • 2023-04-09
              • 2017-07-21
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多