Use case:
export default function() {
multiple http calls.
if any singe http call fails, stop executing the rest of the code with check and fail statement.
}
export function teardown(){
some code
}
My question is: will teardown() be executed even after default function is aborted? In my case, teardown is always needed at the end of test execution, even after the test aborts in the middle of a process. Cucumber test framework has such handy feature, but I tried with K6, it looks like it is not able to do that.
Thanks.
the teardown function is always executed, regardless of the test result.
To abort the default function, you on any http failure, you can create a custom metric, let’s say failedRequestCounter and create a threshold with abortOnFail parameter.
See example here:
import http from 'k6/http'
import { Counter } from 'k6/metrics'
import { sleep, check as loadTestingCheck } from "k6";
let failedRequestCounter = new Counter('failedRequestCounter');
export let options = {
thresholds: {
failedRequestCounter: [{ threshold: 'count==0', abortOnFail: true }], // abort the test on any failed requests
},
vus: 1,
duration: '30s',
}
let check = function (obj, conditionArray, tags) {
let result = loadTestingCheck(obj, conditionArray, tags || {});
failedRequestCounter.add(!result);
return result;
}
export default function () {
let res = http.get('https://test-api.loadimpact.com/public/crocodiles/')
check(res.status, {
"API is working": (status) => status === 200
});
res = http.get('https://test-api.loadimpact.com/public/crocodiles/a') // 404
check(res.status, {
"some other check": (status) => status === 201
});
sleep(1);
}
export function teardown(){
console.log("terdown executed");
}
Unfortunately, teardown() won’t always be called in the current k6 version, if the script gets aborted by threshold, or some other way. I recently fixed that behavior, among other things, in #1390, but that has only been merged in #1007, it hasn’t been merged in master or been officially released yet.