karatelabs/karate · warning

karate.request is only available in mock context

Error message

karate.request is only available in mock context

What it means

karate.request is only meaningful when Karate is acting as an HTTP mock server: it returns the body of the request currently being handled by the mock. KarateJs's getRequest() checks for a mock handler; if the KarateJs instance is not wired to a MockHandler, it logs this warning and returns null instead of throwing.

Solutions

  1. Only reference karate.request inside mock-handler context (e.g. code evaluated by the mock when a request arrives).
  2. Start/wire the mock (karate.start / MockHandler) before code that reads karate.request runs.
  3. Guard the JS: `if (karate.request) { ... }` or read the actual request object passed into your mock handler callback instead.
  4. If you meant the current HTTP response/request in a client test, use the correct variable (e.g. response / request in feature scope), not karate.request.

Example fix

// before (client-side test)
var body = karate.request; // warns, always null outside mock

// after (inside mock handler context)
// mock handler JS:
function fn(request) { return { body: request.body }; }
// or in mock scenario: read the built-in request variable, not karate.request
Defensive patterns

Strategy: type-guard

Validate before calling

// JS guard before use
var req = karate.request;
if (req !== null && typeof req === 'object') { /* in mock context */ }

Type guard

function inMockContext(karate) { try { return karate.request != null; } catch (e) { return false; } }

Try / catch

// returns null (does not throw); null-check the property read
var body = karate.request;
if (body == null) {
  // not in mock context — use feature-scope request/response instead
}

Prevention

When it happens

Trigger: Evaluating `karate.request` (a JS property getter backed by getRequest()) inside a scenario, JS block, or embedded KarateJs instance where mockHandler is null — i.e. any non-mock execution: normal API test run, UI run, or custom runner without a mock attached.

Common situations: Copying mock-request helper code (meant for karate.mock()/MockHandler scenarios) into a regular feature test; running the same feature both as a mock handler and as a client test; typo in setup where the mock server was never started before evaluating the JS.

Understand the failure class

Background: "Invalid state transition" errors: "status must be X, actually Y", "already rejected/charging/uninstalled", "cannot ... while running" — what they mean when a library rejects your call — this error's family across 31 libraries.

Related errors


AI-assisted analysis of karatelabs/karate@a22eb90246 (2026-09-12). Data as JSON: /api/errors/e66bd53c26efe56e. Report an issue: GitHub.

Appendix: source

Thrown at karate-core/src/main/java/io/karatelabs/core/KarateJs.java:1051

            if (body != null) {
                builder.body(body);
            }

            // Execute and return the response
            HttpResponse response = builder.invoke();
            return response;
        };
    }

    // ========== Pending Methods Implementation ==========

    /**
     * karate.request - Returns the current mock request (only in mock context).
     * Returns the body content of the current request.
     */
    private Object getRequest() {
        if (mockHandler == null) {
            logger.warn("karate.request is only available in mock context");
            return null;
        }
        io.karatelabs.http.HttpRequest request = mockHandler.getCurrentRequest();
        return request != null ? request.getBodyConverted() : null;
    }

    /**
     * karate.response - In mock context, returns the response variable being constructed
     * (a writable parsed body). In non-mock (test) context, returns the previous {@code HttpResponse}
     * received from an HTTP call, exposing {@code .header(name)} for case-insensitive header
     * lookup as well as {@code .status}, {@code .body}, {@code .headers} and friends.
     * Returns null before any request has been made.
     */
    private Object getResponse() {
        if (mockHandler != null) {
            // In mock context, 'response' is a variable in the engine being constructed
            return engine.get("response");
        }

View on GitHub (pinned to a22eb90246)