vitest-dev/vitest · error · Error

Failed to load custom "defines": ${error.message}

Error message

Failed to load custom "defines": ${error.message}

What it means

Same define-evaluation guard as error 383 but in the VM pool: runVmTests evaluates config.serializedDefines via vm.runInContext inside the VM context (vm.ts:144-153). If the injected define code is invalid, the error is wrapped and rethrown.

Source

Thrown at packages/vitest/src/runtime/workers/vm.ts:151

      context,
      externalModulesExecutor,
    },
    configurable: true,
    enumerable: false,
    writable: false,
  })
  context.__vitest_mocker__ = moduleRunner.mocker

  setupEnv(ctx.config.env, state.metaEnv)

  if (ctx.config.serializedDefines) {
    try {
      runInContext(ctx.config.serializedDefines, context, {
        filename: 'virtual:load-defines.js',
      })
    }
    catch (error: any) {
      throw new Error(`Failed to load custom "defines": ${error.message}`)
    }
  }
  await moduleRunner.mocker.initializeSpyModule()

  const { run } = (await moduleRunner.import(
    entryFile,
  )) as typeof import('../runVmTests')

  try {
    await run(
      method,
      ctx.files,
      ctx.config,
      moduleRunner,
      traces,
    )
  }
  finally {

View on GitHub (pinned to d568f8ce37)

Solutions

  1. JSON.stringify every non-primitive define value.
  2. Read the appended inner error.message for the precise syntax/runtime fault.
  3. Temporarily run with pool 'threads' to confirm the defines work, then fix and re-enable the VM pool.

Example fix

// before
export default defineConfig({
  test: { define: { __CFG: { api: '/v1' } } },
})

// after
export default defineConfig({
  test: { define: { __CFG: JSON.stringify({ api: '/v1' }) } },
})
Defensive patterns

Strategy: validation

Validate before calling

function validateSerializedDefines(source: string) {
  try {
    // mimic runInContext by parsing as a script
    new Function(source)
  } catch (e) {
    throw new Error(`define source is not valid JS: ${(e as Error).message}`)
  }
}

Prevention

When it happens

Trigger: Configuring test.define / vite define with values that serialize to invalid JS, surfaced specifically when running under the vmThreads/vmForks pool. The serialized defines are run inside the freshly created VM context.

Common situations: A define value that is not JSON-stringified (object/function inserted raw); a define key containing characters that break the generated code; switching to the VM pool exposing a define bug that threads tolerated by chance.

Related errors


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