javascriptjsondata-filesk6

How to pass content of json file as url param


I am trying to learn data parameterization. I have a json file with 2 entries:

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

and I manage to print them into the console. However, I am not able into my http.post.

Is there anything wrong with this: const url = 'https://api.example-test.com/user-api/accounts/${randomUser.accountreference}/benefit';

Any better way of passing it on?

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


Solution

  • In order to use template strings in javascript, you need to use the ` quotes, not the ' quotes.

    // 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';