let json = JSON.parse(responseBody); // responseBody是包含整个返回内容的字符串
// 提取某字段的值:
let foobar = json.foo.bar[0].foobar; // 假设结构为 {"foo": {"bar": [{"foobar": 1}, {"baz": 2}]}}
// 想用在自动化测试可以多写点:
let json;
try {
json = JSON.parse(responseBody);
} catch (err) {
tests['Expect response body to be valid JSON'] = false;
tests[`Response body: ${responseBody}`] = true;
console.error(err);
}
返回HTML时
// A. 用正则表达式匹配
let foo = responseBody.match(/foo/g); // g 全局 i 不分大小写 m 多行
tests['blahblahblah'] = foo[0] === 'bar';
// 正则里包含变量时:
let foo = 'xxx';
let bar = responseBody.match(new RegExp(`^${foo}.*$`, 'g');
// B. 用CheerioJS库(可以让你用jQuery语法):
const $ = cheerio.load(responseBody);
$.html() // 整个网页
$('title').text(); // <title>标签里的文字
jQuery replaced by CheerioJS in Postman Sandbox, 2016-08-30
提取请求参数的值
Writing a behaviour driven API testing environment within Postman
// 如果确实要在代码里设global
// 官方的:
postman.setGlobalVariable('variableKey', value); // 同样存成字符串
let bar = postman.getGlobalVariable('variableKey');
postman.clearGlobalVariable('variableKey');
// 或者自己操作 globals 对象
数据文件
不做自动化测试可以跳过这段
Using data variables to run a collection multiple times
Using CSV and JSON data files in the Postman Collection Runner, 2014-10-28
Using variables inside Postman and Collection Runner, 2014-02-20
在collection runner或命令行的Newman里可以加载数据文件