代码之家  ›  专栏  ›  技术社区  ›  Lluís Suñol

在Postman测试中检查响应标头的值

  •  34
  • Lluís Suñol  · 技术社区  · 7 年前

    我想检查来自具体响应标题(“位置”)的值,作为Postman中的测试结果。 在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;
    });
    
    6 回复  |  直到 7 年前
        1
  •  83
  •   Lluís Suñol    7 年前

    我终于找到了解决方案:

    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");
    });
    
        2
  •  17
  •   Irfan Makandar    6 年前

    下面是在测试部分获取特定响应头的另一种方法。。。

    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并对其进行预处理/后处理。

    例如

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

        3
  •  1
  •   leonidv    5 年前

    HeadersList 有方法 has(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
  •  0
  •   Vallabha Vamaravelli    4 年前

    pm.test("Location value is correct", function () {
       pm.expect(pm.response.headers.get('Location')).to.eql('http://google.com');
    });
        5
  •  0
  •   Mirza Sisic    4 年前

    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
  •  0
  •   rmuller    4 年前

    使用 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");
    });