grafana/k6 · error

exported 'setup' must be a function

Error message

exported 'setup' must be a function

What it means

During bundle instantiation, populateExports (internal/js/bundle.go:224) walks the script's exports. Every export that is not a callable function is inspected; for the reserved name 'setup' a non-function value is rejected with this error, because k6 must call setup() once per test to build shared data.

Solutions

  1. Declare setup as a function: `export function setup() { ... }`.
  2. If setup is optional data, move it into a named export k6 ignores (e.g. `setupData`) and read it inside setup/default.
  3. Check for accidental re-exports (`export * from './helpers'`) that publish a non-function `setup`.

Example fix

// before
export const setup = { token: 'abc' };
// after
export function setup() { return { token: 'abc' }; }
Defensive patterns

Strategy: type-guard

Type guard

// static self-check for k6 scripts: reserved exports must be functions
const fs = require('fs');
const src = fs.readFileSync('script.js', 'utf8');
for (const name of ['setup', 'teardown']) {
  const bad = new RegExp(`export\\s+(const|let|var)\\s+${name}\\b`).test(src);
  if (bad) throw new Error(`exported '${name}' must be a function`);
}

Prevention

When it happens

Trigger: Exporting setup as a non-function: `export const setup = ...`, `export let setup = {}`, or `export { obj as setup }` where obj is not a function. Plain default/handle functions are unaffected.

Common situations: Refactoring scripts and turning setup into a data object; copy-paste from examples where setup was partially deleted; name collisions with an imported helper re-exported as setup.

Related errors


AI-assisted analysis of grafana/k6@3fcf5388d7 (2026-08-18). Data as JSON: /api/errors/ab9fb0b2530c4caa. Report an issue: GitHub.

Appendix: source

Thrown at internal/js/bundle.go:224

					return
				}
				dec := json.NewDecoder(bytes.NewReader(data))
				dec.DisallowUnknownFields()
				if err = dec.Decode(&b.Options); err != nil {
					if uerr := json.Unmarshal(data, &b.Options); uerr != nil {
						// Beautify the error so we can try to show the user the key and potential value that is failing to parse
						uerr = beautifyOptionsJSONUnmarshalError(data, uerr)
						err = errext.WithAbortReasonIfNone(
							errext.WithExitCodeIfNone(uerr, exitcodes.InvalidConfig),
							errext.AbortedByScriptError,
						)
						return
					}
					b.preInitState.Logger.WithError(err).Warn("There were unknown fields in the options exported in the script")
					err = nil
				}
			case consts.SetupFn:
				err = errors.New("exported 'setup' must be a function")
				return
			case consts.TeardownFn:
				err = errors.New("exported 'teardown' must be a function")
				return
			}
		}
	})
	<-ch
	if err != nil {
		return err
	}

	if len(b.callableExports) == 0 {
		return errors.New("no exported functions in script")
	}

	return nil
}

View on GitHub (pinned to 3fcf5388d7)