后置脚本

后置脚本是在请求发送完成后执行的代码片段。主要用来断言请求返回的结果是否正确、将请求返回的结果数据写入环境变量等。

使用示例

断言请求返回的结果是否正确

  1. // pm.response.to.have 示例
  2. pm.test('返回结果状态码为 200', function() {
  3. pm.response.to.have.status(200);
  4. });
  5. // pm.expect() 示例
  6. pm.test('当前为正式环境', function() {
  7. pm.expect(pm.environment.get('env')).to.equal('production');
  8. });
  9. // response assertions 示例
  10. pm.test('返回结果没有错误', function() {
  11. pm.response.to.not.be.error;
  12. pm.response.to.have.jsonBody('');
  13. pm.response.to.not.have.jsonBody('error');
  14. });
  15. // pm.response.to.be* 示例
  16. pm.test('返回结果没有错', function() {
  17. // assert that the status code is 200
  18. pm.response.to.be.ok; // info, success, redirection, clientError, serverError, are other variants
  19. // assert that the response has a valid JSON body
  20. pm.response.to.be.withBody;
  21. pm.response.to.be.json; // this assertion also checks if a body exists, so the above check is not needed
  22. });

将请求返回的结果数据写入环境变量

  1. // 获取 JSON 格式的请求返回数据
  2. var jsonData = pm.response.json();
  3. // 将 jsonData.token 的值写入环境变量
  4. pm.environment.set('token', jsonData.token);

更多示例

  1. 更多测试/断言示例
  2. 使用变量(环境变量、全局变量、临时变量)示例
  3. 脚本内发送接口请求
  4. 读取接口请求信息
  5. 加密/解密