Re-run the setup() function or re-generate the token every few minutes in a long duration test

Hi team,

The first thing I do in the “setup” stage is to get a bearer token, and then in the test code, I use that token to perform operations. However, the bearer token has an expiration of an hour, so if the duration of my test is longer, the token is no longer valid and the test fails.

Would there be any way to rerun the “setup” step after an hour, to get the bearer token again?

TIA

Hi @Niveditha,
if you are running a single scenario you could use the k6/execution.scenario.startTime property for computing the elapsed time.

We have an example in your documentation for a similar operation.

Let me know if it helps.

Hi @Niveditha,
I see you deleted the latest comments, did you find a solution?

Hi, @codebien I just solved the issue by following your reply. Thank you so much. Following is the code I have added in my setup.js file

import exec from 'k6/execution';
var expired = 0;

export const options = {
  scenarios: {
    bearerToken: {
      // peak scenario name
      executor: 'ramping-arrival-rate',
      startRate: 0,
      timeUnit: '1s',
      preAllocatedVUs: 5,
      stages: [{
          target: 2,
          duration: "1s"
        },
        {
          target: 2,
          duration: "30s"
        },
        {
          target: 0,
          duration: "1s"
        },
      ],
      gracefulStop: 0,
    },
  },

expired = exec.scenario.startTime;
  let currenttime = new Date() - expired;
  console.log(expired);
  //1 hour = 59 minutes 3540000
  if(expired => 1000 ){
    setup();
  }
}