Unable to refer the values from csv and store it to POST request variable

We are trying to parameterize username from the csv file. The script works fine if i hardcode the value in Email field

let response = http.post(
https://stage-demo.com//account/login’,
{
Email: “stage@demo.com”,
Password: ‘Password1’,
NewAuth: ‘true’,
MX1Enabled: ‘True’,
ReturnUrl: ‘’,
__rtoken: rtoken,
},

But it fails if i declare it as a variable name so that i can read the data from csv file.

let response = http.post(
https://stage-demo.com//account/login’,
{
Email: user.username,
Password: ‘Password1’,
NewAuth: ‘true’,
MX1Enabled: ‘True’,
ReturnUrl: ‘’,
__rtoken: rtoken,
},

Here is the complete script:
import { sleep, group, check } from ‘k6’
import http from ‘k6/http’
import jsonpath from ‘https://jslib.k6.io/jsonpath/1.0.2/index.js’;
import papaparse from ‘https://jslib.k6.io/papaparse/5.1.1/index.js’;
import { SharedArray } from ‘k6/data’
import { scenario, vu, exec } from ‘k6/execution’
import { htmlReport } from “K6 Load Test: <%= title %>”;
import { textSummary } from ‘https://jslib.k6.io/k6-summary/0.0.1/index.js’;

// Load CSV file and parse it
let csvData = papaparse.parse(open(‘./username.csv’), { header: true }).data;

export let options = {
vus: 1, // number of virtual users
//duration: ‘1m’, // test duration
iterations: 1,
};

export default function main() {
// Get a unique user for each iteration
let user = csvData[__VU % csvData.length];
console.log("User detail : " + JSON.stringify(user));

    let res = http.get('https://stage-demo.com//', {
        headers: {
          'upgrade-insecure-requests': '1',
          'user-agent':
            'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36',
          'sec-ch-ua': '"Chromium";v="122", "Not(A:Brand";v="24", "Google Chrome";v="122"',
          'sec-ch-ua-mobile': '?0',
          'sec-ch-ua-platform': '"Windows"',
        },
      })
      
      //Correlation code for rtoken
  
      let rtoken = res.html().find('input[name=__rtoken]').first().attr('value')
      console.log('rtoken: ' + rtoken)
  
      check(res, { 'HomePage Loaded Successfully' : (r) => r.body.includes('stagedemo & Hospice LLC'),})
      //check(response, { 'verify homepage text': (r) => r.body.includes('stagedemo & Hospice LLC'),});
        
    let      response = http.post(
        'https://stage-demo.com//account/login',
        {
          Email: "${user.username}",
          Password: 'Password1',
          NewAuth: 'true',
          MX1Enabled: 'True',
          ReturnUrl: '',
          __rtoken: rtoken,
        },
        {
          headers: {
            accept: '*/*',
            'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
            referer: 'https://stage-demo.com//',
            'user-agent':
              'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36',
            'xperf-login.careanyware.com-requested-with': 'XMLHttpRequest',
            'sec-ch-ua': '"Chromium";v="122", "Not(A:Brand";v="24", "Google Chrome";v="122"',
            'sec-ch-ua-mobile': '?0',
            'sec-ch-ua-platform': '"Windows"',
            traceparent: '00-52fa03d3e4c24c5b850ef65ef836649f-06aef4e46a894cf9-01',
          },
        }
      )
    
  //  Correlation code for token and refresh token
  
  let refreshToken = jsonpath.query(response.json(), '$.Data.RefreshToken')[0]
  
  let token = jsonpath.query(response.json(), '$.Data.Token')[0]
  
  console.log('Token: ' + token, ' / RefreshToken: ' + refreshToken)
  console.log('UniqueUsername: ' , user.username)
  
  check(response, { 'Is status 200 ' : (r) => r.status === 200 , 
                    'Successful login': r => r.body.includes('"Success":true'), })

                    response = http.post(
                        'https://stage-demo.com/Account/Token',
                        {
                          token: token,
                          refreshToken: refreshToken,
                          clientId: 'stagedemo.HomeHealth.Web',
                          returnUrl: '',
                          forceAFO: 'false',
                          termsAccepted: 'false',
                          passwordUpdated: 'false',
                          authUrl: 'https://perf-authapi.careanyware.com',
                          secondaryToken: '',
                          secondaryRefreshToken: '',
                          ectId: '',
                          mx1Enabled: '',
                        },
                        {
                          headers: {
                            'content-type': 'application/x-www-form-urlencoded',
                            origin: 'https://stage-demo.com/',
                            referer: 'https://stage-demo.com//',
                            'upgrade-insecure-requests': '1',
                            'user-agent':
                              'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36',
                            'sec-ch-ua': '"Chromium";v="122", "Not(A:Brand";v="24", "Google Chrome";v="122"',
                            'sec-ch-ua-mobile': '?0',
                            'sec-ch-ua-platform': '"Windows"',
                          },
                        }
                      )

        
  response = http.get(
    'https://stage-demo.com/Announcement/Notifications?_=1712127797256',
    {
      headers: {
        accept: '*/*',
        referer: 'https://stage-demo.com/PatientRecord',
        'user-agent':
          'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36',
        'x-bt-currentadmission': '259a4518-d201-46fe-a14e-9bba40f0266e',
        'x-bt-currentpatient': '7ee51e65-ccb5-40ed-a4d9-3a8fa3e39660',
        'x-requested-with': 'XMLHttpRequest',
        'sec-ch-ua': '"Chromium";v="122", "Not(A:Brand";v="24", "Google Chrome";v="122"',
        'sec-ch-ua-mobile': '?0',
        'sec-ch-ua-platform': '"Windows"',
        traceparent: '00-bb4531091a9c487abfe7443ea60b9b20-7fda7896f4314628-01',
      },
    }
  )

  response = http.get(
    'https://stage-demo.com/Patient/AutocompletePatientList?text=&_=1712127797257',
    {
      headers: {
        accept: '*/*',
        referer: 'https://stage-demo.com/PatientRecord',
        'user-agent':
          'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36',
        'x-bt-currentadmission': '259a4518-d201-46fe-a14e-9bba40f0266e',
        'x-bt-currentpatient': '7ee51e65-ccb5-40ed-a4d9-3a8fa3e39660',
        'x-requested-with': 'XMLHttpRequest',
        'sec-ch-ua': '"Chromium";v="122", "Not(A:Brand";v="24", "Google Chrome";v="122"',
        'sec-ch-ua-mobile': '?0',
        'sec-ch-ua-platform': '"Windows"',
        traceparent: '00-bb4531091a9c487abfe7443ea60b9b20-7f303deb6c444b9d-01',
      },
    }
  )

  
  response = http.get(
    'https://stage-demo.com/Patient/Menu?_=1712127797258',
    {
      headers: {
        accept: '*/*',
        referer: 'https://stage-demo.com/PatientRecord',
        'user-agent':
          'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36',
        'x-bt-currentadmission': '259a4518-d201-46fe-a14e-9bba40f0266e',
        'x-bt-currentpatient': '7ee51e65-ccb5-40ed-a4d9-3a8fa3e39660',
        'x-requested-with': 'XMLHttpRequest',
        'sec-ch-ua': '"Chromium";v="122", "Not(A:Brand";v="24", "Google Chrome";v="122"',
        'sec-ch-ua-mobile': '?0',
        'sec-ch-ua-platform': '"Windows"',
        traceparent: '00-bb4531091a9c487abfe7443ea60b9b20-292f995be9524963-01',
      },
    }
  )

  
  
response = http.get('https://stage-demo.com/Account/LogOff', {
  headers: {
    referer: 'https://stage-demo.com/PatientRecord',
    'upgrade-insecure-requests': '1',
    'user-agent':
      'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36',
    'sec-ch-ua': '"Chromium";v="122", "Not(A:Brand";v="24", "Google Chrome";v="122"',
    'sec-ch-ua-mobile': '?0',
    'sec-ch-ua-platform': '"Windows"',
  },
})

check(response, { 'User Successfully Logged out' : (r) => r.body.includes('stagedemo & Hospice LLC')})
  

                
sleep(1);

}

Hi @sattivasudevan

I think, the problem, and the solution is the same as here: Unable to pass value into the body of post request - #2 by bandorko

Variable substitution only works in template strings : JavaScript Template Strings

So you have to use either:

Email: `${user.username}`,

or

Email: user.username,

I hope this helps

Hi @bandorko ,

Thanks for your response. I tried both approach as listed by you. But it didn’t work.
Tried to print the variable using
console.log('UniqueUsername: ’ , user.username)
Here is the response we encountered

INFO[0003] UniqueUsername: undefined.

Thanks
Sattish.

And what is the output of this line of your script?

console.log("User detail : " + JSON.stringify(user));

Hi ,
Thanks for the input. here is the output
User detail : {“username":"demouser@demo.com”,“empfname”:“demo”,“emplname”:“user”} from the test execution

@sattivasudevan , I am not quite sure how file open is supposed to work exactly in K6
But normally, if you want to pass around serialised data between tests - you will use the setup function to export this data
so in your test you can access it

Looking at docs - JavaScript API: open
It seems your approach should work.
However, the issue might be how you access the array index. Maybe check what you get in __VU before you use it to access array index