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

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

我想检查答案是否正确。当响应码为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");
}

});

最佳答案

如果状态代码为 200,这将是将消息记录到控制台的基本内容:

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

如果之后您需要检查响应正文中的内容,您可以执行类似下面示例的操作。

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

它的响应主体是:

{
    "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,它只会运行检查响应代码是否为200:

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

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

关于javascript - Postman 测试 - 使用 http 状态进行调节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54868884/

相关文章:

javascript - angularJS中的WebGL ThreeJS和PhysiJS无法启动物理?

相当于 Rails try 方法的 Javascript

c# - 通过 http 异步发送数据

unit-testing - 如何在不引入风险的情况下测试遗留应用程序(并采用测试驱动开发)?

python-3.x - 使用 tox 在后台运行命令

javascript - React js 状态未在表单上设置

php - 具有 PHP 或 Python 绑定(bind)的可编写脚本的 JavaScript 解释器?

c++ - 使用 winsock 发送 POST 数据(并使用 PHP 服务器端脚本接收它们)

java - 如何发送带有 json 正文和 url 参数的 http 帖子?

java - 测试网络应用程序