Why build didn't fail at TypeError in K6

We use K6 to run all our functional tests and configuration of our tests are based on this thread

I have found an issue with our build today that there was a TypeError and build aborted with an exit 0 code and it was marked as success.

ERROR - ERRO[0313] TypeError: Cannot read property 'value' of undefined

I was hoping this type error would have resulted in a non zero exit code but our build was green even though it was exited at that particular error.

  data_received........................................................: 2.7 MB 9.2 kB/s
    data_sent............................................................: 243 kB 833 B/s
  ✓ failedTestCases......................................................: 0      0/s

We are adding more assertions statement in the function to tackle this and I was wondering if you have any other tip or suggestion.

This seems like it was a script error that just aborted some iterations prematurely. This will not cause k6 to return a non-zero exit code, only crossed thresholds will. So I suggest wrapping your code in a try / catch block and if there’s an exception. Something like this:

import { Counter } from 'k6/metrics'

let failures = new Counter('failed_iterations');

export let options = {
    thresholds: {
        failed_iterations: ['count==0'],
    }
};

export default function () {
    try {
        if (Math.random() < 0.5) {
            console.log('throwing an error');
            throw new Error('random script error');
        }
    } catch (e) {
        failures.add(1);
    }
};
1 Like