Postman 测试 - 使用 http 状态进行调节

Postman Tests - Conditioning with http status

我想检查一下答案是否正确。当响应码为200或500时,它是正确的。后者需要区分响应主体中的字符串是正确的还是不正确的。应该是单测的。

我已经尝试过简单的 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");
}

});

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

试试这个异步发送请求:

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)
  }
}

如果状态代码是 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 code 是否是 200:

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

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