Postman-to-k6 pm.sendRequest

I saw a post already about pm.sendRequest not being supported

I also have no idea how can I change my part of a code. Here’s the code:

//if the token is missing or invalid, new token is retrieved

  pm.sendRequest(echoPostRequest, function(err, res) {
    console.log(err ? err : res.json());
    if (err === null) {
      console.log("Saving the token and expiry date");
      var responseJson = res.json();
      pm.environment.set("accessToken", responseJson.access_token);

Thank you in advance for helping out :smiley:

Hey @Bruno! You’ll need to know what echoPostRequest looks like (is it just a URL or are there POST data parameters as well?), but a rough equivalent in k6 would be:

const res = http.post(
  echoPostRequest,
  {
    // insert POST data here
  },
);

// if the response is a JSON object that contains a `access_token` property:
if (res.json() && res.json().access_token) { 
  // store it somewhere
  vars['access_token'] = res.json().access_token;
  console.log("Access token: " + vars['access_token']);
}

The vars array would need to be declared in the global/init scope - that allows you to access it from anywhere else in your script code (which is basically the equivalent of what you do with pm.environment.set).

If the POST data is application/json, you may need to JSON.stringify the POST data and add the Content-Type header like this:

const res = http.post(
  echoPostRequest,
  JSON.stringify({
    // insert POST data here
  }),
  {
    headers: {
      'Content-Type': 'application/json',
    }
  }
);
1 Like