【问题标题】:How to pass content of json file as url param如何将json文件的内容作为url参数传递
【发布时间】:2021-11-13 13:59:28
【问题描述】:

我正在尝试学习数据参数化。 我有一个包含 2 个条目的 json 文件:

[
        {
          "accountreference": "4157804914681"
        },
        {
          "accountreference": "4157804925075"
        }
]

我设法将它们打印到控制台中。但是,我无法进入我的 http.post。

这有什么问题吗: const url = 'https://api.example-test.com/user-api/accounts/${randomUser.accountreference}/benefit';

有没有更好的方法来传递它?

import http from "k6/http";
import { check, sleep } from "k6";
import { SharedArray } from 'k6/data';

// Test setup
export let options = {
    stages: [
        { duration: '3s', target: 1 },
        { duration: '3s', target: 0 }, // scale down. Recovery stage.
      ],
      thresholds: {
        // 90% of requests must finish within 400ms, 95% within 800, and 99.9% within 2s.
        http_req_duration: ['p(90) < 400', 'p(95) < 800', 'p(99.9) < 2000'],
      },
};

const data = new SharedArray('accountRef', function () {
    // here you can open files, and then do additional processing or generate the array with data dynamically
    const f = JSON.parse(open('./accountRef.json'));
    return f; // f must be an array[]
  });

export default () => {
    const randomUser = data[Math.floor(Math.random() * data.length)];
    console.log(`${randomUser.accountreference}`);
    const url = 'https://api.example-test.com/user-api/accounts/${randomUser.accountreference}/benefit';

    const params = {
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer blahblahPk9tjDdQ`,
        },
      };
    const data1 = "{ \"amount\": 20000, \"external_reference\": \"mba-bcbdac6-024-m-2155667\",  \"transaction_attributes\": { \"channel\": \"POP\"}}";

    // execute
    let res = http.post(url,data1,params);
    check(res, { 
          "Create user response status code is 201": (r) => r.status == 201,
      }
    );

    // Short break between iterations
    sleep(1);
  
  };

results

【问题讨论】:

    标签: javascript json data-files k6


    【解决方案1】:

    为了在 javascript 中使用模板字符串,您需要使用 ` 引号,而不是 ' 引号。

    // Write this:
    const url = `https://api.example-test.com/user-api/accounts/${randomUser.accountreference}/benefit`;
    
    // Not this:
    const url = 'https://api.example-test.com/user-api/accounts/${randomUser.accountreference}/benefit';
    

    【讨论】:

    • 非常感谢阿什利。你是个天才,它行得通。
    • 已解决。谁负责将其标记为已解决_
    • 你负责。应该有一个绿色勾号,您可以单击我的答案旁边的下一步
    猜你喜欢
    • 2012-03-17
    • 1970-01-01
    • 2015-02-19
    • 1970-01-01
    • 2017-03-04
    • 2019-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多