资料链接:https://stackoverflow.com/questions/36339292/how-to-check-if-responsebody-does-not-contain-string-in-postman-tests
Postman编写断言时,判断返回结果中是否包含某字符串可用:
tests["Body matches string"] = responseBody.has("string_you_want_to_search");
或
pm.test("Body matches string", function () {
pm.expect(pm.response.text()).to.include("string_you_want_to_search");
});
如果想判断是否不包含某字符串,可使用下列方法:
方法一:
pm.test("Body matches string", function () {
pm.expect(pm.response.text()).to.not.include("string_you_want_to_search");
});
这一方法只适用于Postman的standalone版本,桌面app无法使用。
方法二:
tests["Body does not have supplied string"] = !(responseBody.has("string_you_want_to_search"));
方法三:
var data = JSON.parse(responseBody);
tests["Body does not contain string_you_want_to_search"] = data.search("string_you_want_to_search") < 0;
这个方法默认返回结果为JSON格式,如返回HTML格式,可使用cheerio对其作解析:
var cheerio = require('cheerio');
$ = cheerio.load(responseBody);
var reg = RegExp("string_you_want_to_search",'g'); //这里用了全局匹配
tests["Body does not contain string_you_want_to_search"] = $.text().search(reg) < 0; //search不到字符串返回-1