You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

k6测试报错:Cannot read property 'accessToken' of undefined求助

问题分析

报错TypeError: Cannot read property 'accessToken' of undefined的核心原因是:你在登录请求的post回调中错误使用了pm.response,同时环境变量的读写方式不符合postman-to-k6 shim的实际逻辑。

修复后的代码
// Auto-generated by the postman-to-k6 converter

import "./libs/shim/core.js";
import "./libs/shim/urijs.js";

export let options = { maxRedirects: 4 };

const Request = Symbol.for("request");
postman[Symbol.for("initial")]({
  options,
  environment: {
    BASE_URL: "cannot share",
    AUTH_URL: "{{BASE_URL}}/login",
    TOKEN: ""
  }
});

export default function() {
  postman[Request]({
    name: "POST_Authentication",
    id: "5d152f56-5305-4be2-a790-1294612da9db",
    method: "POST",
    address: "{{AUTH_URL}}",
    data:
      '{\r\n\t"username": "example@gmail.com",\r\n\t"password": "hidden"\r\n}',
    post(response) {
      // 用回调传入的response参数解析响应,直接修改环境变量对象
      const respData = response.json();
      postman.environment.TOKEN = respData.accessToken;
    }
  });

  postman[Request]({
    name: "Get - Product by ID",
    id: "e3462baf-8423-4c5b-8421-6232c8a59445",
    method: "GET",
    address: "{{BASE_URL}}/module/all",
    auth(config) {
      // 直接从环境变量对象读取TOKEN
      config.headers.Authorization = `Bearer ${postman.environment.TOKEN}`;
    }
  });
}
关键修改说明
  • 响应数据获取:postman-to-k6的shim不会自动把响应绑定到pm.response上,必须使用post回调传入的response参数来解析返回内容。
  • 环境变量操作:放弃postman.setEnvironmentVariable和pm[Var]的用法,直接通过postman.environment对象读写变量,这是该shim实际支持的方式。
  • Auth回调简化:auth回调无需额外参数,直接访问postman.environment即可拿到TOKEN。

调试建议:可以在post回调中添加console.log(response.body),确认登录接口返回的JSON结构确实包含accessToken字段,避免因接口返回格式不符导致的问题。

内容的提问来源于stack exchange,提问作者Ashir

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 00:42:55