如何在Postman的新pm.*API中使用条件语句?

Gue*_*z0r 3 testing chai postman

我有一个关于如何使用带有条件语句的新pm.*API的问题.请查看以下示例代码

if(pm.test("Status code is 200", function() {pm.expect(pm.response.code).to.equal(300);
})){

var token = pm.response.headers.get("Authorization");
pm.environment.set("JWT Token", token.substr(7));

pm.test("Response body is empty ", function () {
    pm.expect(pm.response.text().length).to.equal(0);
});
}

console.log(pm.test("Status code is 200", function() {pm.expect(pm.response.code).to.equal(300)}));
Run Code Online (Sandbox Code Playgroud)

因为我可能想要执行某些测试,例如,只有当返回200时我才想使用if.但是,当我故意将等值更改为300只是为了检查它是否有效时,即使第一次测试失败,也会运行两个测试并设置变量.

对于断言,console.log返回一个空对象而不是true/false.如果我使用类似的东西

console.log(pm.expect(pm.response.code).to.equal(300));
Run Code Online (Sandbox Code Playgroud)

我将收到一条错误消息:评估测试脚本时出错:AssertionError:预期200等于300

有谁知道如何解决这个问题?

干杯

Gue*_*z0r 11

我也在邮递员的github上问了这个问题,我得到了帮助.显然pm.test不返回测试结果,因为你可以在一个pm.test中有多个断言,并且这些断言是异步执行的.

以下代码按预期工作:

pm.test("Status code is 200", function() {
  pm.expect(pm.response.code).to.equal(200);
});

(pm.response.code===200 ? pm.test : pm.test.skip)("Response body is empty", function () {

    pm.expect(pm.response.text().length).to.equal(0);

    var token = pm.response.headers.get("Authorization");
    pm.environment.set("JWT Token", token.substr(7));
});
Run Code Online (Sandbox Code Playgroud)