I want to store an id in a setup section, what I got when I upload a file for an endpoint, and after that, I need to get back the uploaded element in the default section multiple times. I tried to use a helper function with a setter and getter but it gave back undefined in the default function. Is there any easy way to store a number between the setup function and the default?
Yes, that is possible and it is documented and explained in Test Life Cycle – Setup and Teardown Stages.
The setup function can return an object, which is then passed to each VU's default function as the first parameter:
import http from 'k6/http';
export function setup() {
const res = http.get('https://httpbin.test.k6.io/get');
return { data: res.json() };
}
export function teardown(data) {
console.log(JSON.stringify(data));
}
export default function (data) {
console.log(JSON.stringify(data));
}
There are some restrictions regarding the data types you can pass between setup and default or teardown, but you mentioned it being a number which should be no problem. Basically anything is supported, as long as it can be serialized to and from JSON.
For your use-case it would probably look like this:
import http from 'k6/http';
const file = open('./path/to/file', 'b');
export function setup() {
const uploadData = {
fileUploadFieldName: http.file(file, 'yourfilename'),
};
const res = http.post('https://example.com/upload', uploadData);
return { documentId: res.json('document.id') };
}
export default function (data) {
const res = http.get(http.url`https://example.com/documents/${data.documentId}`);
// ...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With