vitest-dev/vitest · error · Error

This command can only be called inside a test file.

Error message

This command can only be called inside a test file.

What it means

Thrown by the resolveTracesPath helper (used by startChunkTrace/stopChunkTrace) when testPath is missing. The helper computes the trace.zip output directory from dirname(testPath) and the test filename; without a test file it cannot place the trace.

Source

Thrown at packages/browser-playwright/src/commands/trace.ts:144

      return
    }
    await context.context.tracing.groupEnd()
    return
  }
  throw new TypeError(`The ${context.provider.name} provider does not support tracing.`)
}

function parseLocation(context: BrowserCommandContext, stack?: string): ParsedStack | undefined {
  if (!stack) {
    return
  }
  const parsedStacks = context.project.browser!.parseStacktrace(stack)
  return parsedStacks[0]
}

function resolveTracesPath({ testPath, project }: BrowserCommandContext, name: string) {
  if (!testPath) {
    throw new Error(`This command can only be called inside a test file.`)
  }
  const options = project.config.browser!.trace
  const sanitizedName = `${project.name.replace(/[^a-z0-9]/gi, '-')}-${name}.trace.zip`
  if (options.tracesDir) {
    return resolve(options.tracesDir, sanitizedName)
  }
  const dir = dirname(testPath)
  const base = basename(testPath)
  return resolve(
    dir,
    '__traces__',
    base,
    `${project.name.replace(/[^a-z0-9]/gi, '-')}-${name}.trace.zip`,
  )
}

export const deleteTracing: BrowserCommand<[{ traces: string[] }]> = async (
  context,

View on GitHub (pinned to d568f8ce37)

Solutions

  1. Invoke tracing commands only from within a running test so testPath is set.
  2. Move the tracing call into the it/test body.
  3. For non-test scenarios, write traces manually via Playwright's tracing API with an explicit dir.

Example fix

// before (no test context)
await context.commands.stopChunkTrace({ name: 'boot' })

// after (inside a test)
test('traced', async () => {
  await context.commands.stopChunkTrace({ name: 'traced' })
})
Defensive patterns

Strategy: validation

Validate before calling

if (!context.testPath) {
  throw new Error('trace path resolution requires a test file context')
}
resolveTracesPath(context, name)

Type guard

function inTestFile(c: BrowserCommandContext): c is BrowserCommandContext & { testPath: string } {
  return typeof c.testPath === 'string' && c.testPath.length > 0
}

Prevention

When it happens

Trigger: Any tracing command that resolves an output path is invoked from a context without a bound testPath (setup, global hooks, or a synthesized command context).

Common situations: Calling tracing helpers from beforeAll/globalSetup, or a plugin that issues trace commands outside the test task graph.

Related errors


AI-assisted analysis of vitest-dev/vitest@d568f8ce37 (2026-08-03). Data as JSON: /data/errors/e17aed2ac24cecdf.json. Report an issue: GitHub.