Search code examples
k6

Carrying on data from a scenario to the next in k6 load test


I have the following scenarios setup for a load test, and they are expected to run in series:

export let options = {
  scenarios: {
    companyScenario: {
      executor: 'per-vu-iterations',
      exec: 'runCompanyScenario',
      vus: 1,
      iterations: 1,
      maxDuration: '2s',
    },
    employeeScenario: {
      executor: 'per-vu-iterations',
      exec: 'runEmployeeScenario',
      vus: 1,
      iterations: 1,
      maxDuration: '10s',
      startTime: '2s',
    }
  },
};

I'm looking for a way to store the ID of a resource created in the first scenario ("companyScenario"), which is given as part of a response, and then use that ID as part of payload in the next scenario ("employeeScenario").

I tried to use a global constant approach, but the value is lost in between.

Anybody has a hint?


Solution

  • From your scenario definitions, it looks like you are (ab)using scenarios to implement a test lifecycle with a setup phase. k6 already supports a setup function that will be run once before the actual test (scenarios) start and that can pass data to the test function(s). Since your first scenario runs only a single VU for a single iteration, you should move its implementation to the setup function instead.

    More info and examples in the k6 test lifecycle docs

    export let options = {
      scenarios: {
        employeeScenario: {
          executor: 'per-vu-iterations',
          exec: 'runEmployeeScenario',
          vus: 1,
          maxDuration: '10s',
        },
      },
    };
    
    export function setup() {
      // create resource(s) and collect ids(s) to array
    
      return ids;
    }
    
    export function runEmployeeScenario(ids) {
      // ids argument contains the result of the setup function.
    }
    

    Use the teardown function to clean up after your testrun has completed.


    Alternatively, have a single scenario/function which performs both your calls:

    export default function() {
      // create resource(s) and collect id(s) to array
      const ids = [ ... ];
      // use the ids from the array: for (id of ids) { ... }
    }
    

    This should work the same, given that both your scenarios run a single VU for exactly one iteration. Scenarios are most useful when you have independent VUs that perform independent operations in parallel with different request rates.