grafana/k6 · error

provided selector is empty

Error message

provided selector is empty

What it means

NewSelector (selectors.go:45-56) parses every selector used by page.$, page.$$, page.waitForSelector and locators. An empty string has no parts to parse, so it fails fast with 'provided selector is empty' instead of querying the DOM with a meaningless selector.

Source

Thrown at internal/js/modules/k6/browser/common/selectors.go:51

type SelectorPart struct {
	Name string `json:"name"`
	Body string `json:"body"`
}

type Selector struct {
	Selector string          `json:"selector"`
	Parts    []*SelectorPart `json:"parts"`

	// By default chained queries resolve to elements matched by the last selector,
	// but a selector can be prefixed with `*` to capture elements resolved by
	// an intermediate selector.
	Capture *int `json:"capture"`
}

func NewSelector(selector string) (*Selector, error) {
	if selector == "" {
		return nil, errors.New("provided selector is empty")
	}

	s := Selector{
		Selector: selector,
		Parts:    make([]*SelectorPart, 0, 1),
		Capture:  nil,
	}
	err := s.parse()
	return &s, err
}

func (s *Selector) appendPart(p *SelectorPart, capture bool) error {
	s.Parts = append(s.Parts, p)
	if capture {
		if s.Capture != nil {
			return errors.New("only one of the selectors can capture using * modifier")
		}
		s.Capture = new(int)

View on GitHub (pinned to 93accf6570)

Solutions

  1. Validate the selector is a non-empty string before passing it to browser APIs
  2. Filter empty entries out of data-driven selector arrays before iterating
  3. Fail fast with a clear message when a selector-producing config value is missing

Example fix

// before
const sel = selectors[i]; // possibly ''
await page.waitForSelector(sel);

// after
const sel = selectors[i];
if (!sel) throw new Error(`selector at index ${i} is empty`);
await page.waitForSelector(sel);
Defensive patterns

Strategy: validation

Validate before calling

if (typeof selector !== 'string' || selector.trim() === '') {
  throw new Error(`invalid selector: ${JSON.stringify(selector)}`);
}
await page.waitForSelector(selector);

Type guard

const isNonEmptySelector = (s) => typeof s === 'string' && s.trim().length > 0;

Prevention

When it happens

Trigger: page.$(''), page.waitForSelector(''), page.locator(''); a selector built from an undefined/null/empty variable; template literals where a parameter is missing; empty entries in data-driven selector arrays.

Common situations: Parameterized selectors from CSV/JSON data containing empty cells; env-driven selectors where the variable was never set; destructuring mistakes producing undefined stringified to ''.

Related errors


AI-assisted analysis of grafana/k6@93accf6570 (2026-08-15). Data as JSON: /api/errors/d08ee3155c22b8a7. Report an issue: GitHub.