grafana/k6 · error

the function passed to each() failed: %w

Error message

the function passed to each() failed: %w

What it means

Selection.Each wraps the JS callback: if the sobek function invoked per matched element returns an error, it is re-thrown wrapped as "the function passed to each() failed". The root cause is an exception inside the user's each() callback in the test script, raised via common.Throw in the JS runtime.

Source

Thrown at js/modules/k6/html/html.go:375

}

func (s Selection) Children(def ...string) Selection {
	if len(def) == 0 {
		return Selection{s.rt, s.sel.Children(), s.URL}
	}

	return Selection{s.rt, s.sel.ChildrenFiltered(def[0]), s.URL}
}

func (s Selection) Each(v sobek.Value) Selection {
	sobekFn, isFn := sobek.AssertFunction(v)
	if !isFn {
		common.Throw(s.rt, errors.New("the argument to each() must be a function"))
	}

	fn := func(idx int, _ *goquery.Selection) {
		if _, err := sobekFn(v, s.rt.ToValue(idx), selToElement(Selection{s.rt, s.sel.Eq(idx), s.URL})); err != nil {
			common.Throw(s.rt, fmt.Errorf("the function passed to each() failed: %w", err))
		}
	}

	return Selection{s.rt, s.sel.Each(fn), s.URL}
}

func (s Selection) Filter(v sobek.Value) Selection {
	switch val := v.Export().(type) {
	case string:
		return Selection{s.rt, s.sel.Filter(val), s.URL}

	case Selection:
		return Selection{s.rt, s.sel.FilterSelection(val.sel), s.URL}
	}

	sobekFn, isFn := sobek.AssertFunction(v)
	if !isFn {
		common.Throw(s.rt, errors.New("the argument to filter() must be a function, a selector or a selection"))

View on GitHub (pinned to 01ffac6f24)

Solutions

  1. Fix the exception raised inside the each() callback (see the wrapped error/stack)
  2. Wrap callback logic in try/catch inside the script if failures are expected
Defensive patterns

Strategy: try-catch

When it happens

Trigger: Thrown at js/modules/k6/html/html.go:375 when the library encounters an invalid state.

Common situations: See trigger scenarios.


AI-assisted analysis of grafana/k6@01ffac6f24 (2026-08-18). Data as JSON: /api/errors/41de64c7dd65d7b2. Report an issue: GitHub.