【问题标题】:Postman Tests - Conditioning with http statusPostman 测试 - 使用 http 状态进行调节
【发布时间】:2019-07-19 00:21:56
【问题描述】:

我想检查答案是否正常。响应码为 200 或 500 时要么正确,要么正确。后者需要区分响应正文中的 String 是正确还是不正确。它应该在一个测试中。

我已经尝试过简单的 if 子句,但它们不起作用。

pm.test("response is ok", function(){
    if(pm.response.to.have.status(200)){
        //do things
    }     
});

编辑:

我使用的解决方案是

pm.test("response is valid", function(){
if(pm.response.code === 200){
    //is ok
} else if (pm.response.code === 500){
    if(pm.expect(pm.response.json().message).to.include("xyz")){
        //is ok
    } else {
       pm.expect.fail("Error 500"); 
    }
} else {
    pm.expect.fail("statuscode not 200 or 500");
}

});

【问题讨论】:

    标签: javascript http testing http-status-code-404 postman


    【解决方案1】:

    如果状态码是200,这将是一个基本的东西,会将该消息记录到控制台:

    pm.test('Check Status', () => {
        if(pm.response.code === 200) {
            console.log("It's 200")
        }
    })
    

    如果您之后需要检查response body 中的内容,您可以执行以下示例。

    这只是向http://jsonplaceholder.typicode.com/posts/1发送一个简单的GET请求

    它的响应正文是:

    {
        "userId": 1,
        "id": 1,
        "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
        "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
    }
    

    我们可以在Tests 选项卡中添加一个检查,以确认id 属性的值为1,它只会在response code200 时运行此检查:

    if(pm.response.code === 200) {
        pm.test('Check a value in the response', () => {
            pm.expect(pm.response.json().id).to.eql(1)
        })
    }
    

    这是一个非常基本且非常简单的示例,说明您可以做什么。根据您自己的上下文,它会更复杂,但希望它能解释您如何做到这一点。

    【讨论】:

    • 谢谢。 “pm.respone.code ===200”和 pm.expect.* 是我需要的。我在问题中添加了我的解决方案。
    • 我来这里是为了寻找答案,然后我找到了官方的做法。在 Postman 文档中有描述:learning.postman.com/docs/writing-scripts/script-references/… 关键部分是 "pm.expect(pm.response.code).to.be.oneOf([201,202]);"
    【解决方案2】:

    请求是异步的还是同步的? 也许您正在尝试检查尚未到达的响应。

    试试这个异步发送请求:

    var xhr = new XMLHttpRequest();
    xhr.open('GET', "https://my-end-point-url", true);
    xhr.send();
    

    然后使用它来处理请求并将响应显示为弹出窗口:

    xhr.onreadystatechange = (e) => {
      if (xhr.readyState == 4 && xhr.status == 200) {
        var response = JSON.parse(xhr.responseText);
        alert(response)
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2018-10-12
      • 2021-07-23
      • 2020-02-28
      • 1970-01-01
      • 1970-01-01
      • 2018-05-18
      • 2019-10-13
      • 2014-03-22
      • 2018-05-03
      相关资源
      最近更新 更多