Skip to main content

ADVANCED

Karate Object API

The karate object is a runtime utility available in JavaScript functions, Karate expressions, and karate-config.js. It provides methods for test control, data manipulation, HTTP access, and system integration.

On this page:

Test Control

Control test execution flow with abort, fail, and pause operations.

MethodDescription
karate.abort()Exit a Scenario early. Combine with conditional logic: * if (condition) karate.abort()
karate.fail(message)Stop test with error message: * if (!response.data) karate.fail('No data')
karate.pause(ms)Sleep in milliseconds. Only active in performance testing unless configure pauseIfNotPerf is true
karate.stop(port)Pause until socket connection on port. For debugging UI tests. Remove after use.
karate.signal(result)Trigger event for listen keyword. Pass data to waiting listener.
karate.listen(timeout)Wait for karate.signal() event. Result available in listenResult variable.
Gherkin
Feature: Test control methods

Scenario: Abort on missing data
Given url 'https://jsonplaceholder.typicode.com'
And path 'users', 99999
When method get
* if (responseStatus == 404) karate.abort()

Scenario: Fail with message
Given url 'https://jsonplaceholder.typicode.com'
And path 'users', 1
When method get
Then status 200
* if (!response.name) karate.fail('User name is required')

Data Manipulation

Transform and filter arrays and objects using functional operations.

MethodDescription
karate.append(...items)Create array from items (can include arrays). Useful for JSON transforms.
karate.appendTo(name, ...items)Append to existing array variable. First arg can be reference or variable name string.
karate.distinct(list)Return unique items from array of strings or numbers.
karate.filter(list, predicate)Filter array. Predicate: (item, [index]) => boolean
karate.filterKeys(map, keys)Extract key-value subset. Keys can be array or JSON object (uses only keys).
karate.forEach(list, function)Iterate array or object. Function: (item, [index]) for arrays, (key, [value], [index]) for objects.
karate.keysOf(object)Return only keys of map-like object.
karate.lowerCase(object)Convert all keys and values to lowercase.
karate.map(list, function)Transform array. Function: (item, [index]) => newItem
karate.mapWithKey(list, key)Transform array of primitives to array of objects with given key.
karate.merge(...maps)Merge multiple JSON objects. Later objects override earlier keys.
karate.range(start, end, [interval])Return array of integers (inclusive). Default interval is 1.
karate.repeat(count, function)Build array or execute function count times.
karate.sizeOf(object)Return size of array or object.
karate.sort(list, function)Sort array. Function: (item) => sortValue. Optional for simple arrays.
karate.valuesOf(object)Return only values of map-like object.

Chain filter, map, and distinct to extract unique names from a filtered subset of users. Use merge to combine configuration objects with later values overriding earlier ones:

Gherkin
Feature: Data manipulation

Scenario: Filter and transform arrays
Given url 'https://jsonplaceholder.typicode.com'
And path 'users'
When method get
Then status 200
* def activeUsers = karate.filter(response, x => x.id <= 5)
* def names = karate.map(activeUsers, x => x.name)
* def uniqueNames = karate.distinct(names)
* match karate.sizeOf(uniqueNames) == 5

Scenario: Merge and sort objects
* def defaults = { timeout: 5000, retries: 3 }
* def overrides = { timeout: 10000 }
* def config = karate.merge(defaults, overrides)
* match config == { timeout: 10000, retries: 3 }
* def items = [{ priority: 2 }, { priority: 1 }, { priority: 3 }]
* def sorted = karate.sort(items, x => x.priority)
* match sorted[0].priority == 1
Avoid JavaScript Loops

Prefer karate.filter(), karate.map(), and karate.forEach() over JavaScript for loops. Use karate.repeat() when you need to execute something a fixed number of times.

Variable Management

Get and set variables dynamically, especially useful in JavaScript functions and conditional logic.

MethodDescription
karate.get(name, [default])Get variable by name or JsonPath. Returns null if not found. Optional default value.
karate.set(name, value)Set variable immediately. Useful when other code depends on that variable.
karate.set(object)Set multiple variables from JSON object in one operation.
karate.set(name, path, value)Set value at JsonPath within variable. Useful for building payloads dynamically.
karate.remove(name, path)Remove key from JSON or node from XML at path.

Use karate.get() with a default value to safely access nested properties. Use karate.set() with JsonPath to add fields to an existing object:

Gherkin
Feature: Variable management

Scenario: Dynamic variable access
* def config = { timeout: 5000, env: 'test' }
* def timeout = karate.get('config.timeout', 3000)
* match timeout == 5000
* def missing = karate.get('undefined.path', 'default')
* match missing == 'default'

Scenario: Build payload dynamically
* def payload = { userId: 1 }
* karate.set('payload', '$.title', 'Dynamic Title')
* karate.set('payload', '$.body', 'Dynamic content')
* match payload == { userId: 1, title: 'Dynamic Title', body: 'Dynamic content' }

File Operations

Read and write files with support for various formats and path prefixes.

MethodDescription
karate.read(filename)Read file (same as read() function). Auto-converts JSON, XML, CSV.
karate.readAsBytes(filename)Read file as byte array.
karate.readAsStream(filename)Read file as Java InputStream.
karate.readAsString(filename)Read file as string without auto-conversion.
karate.write(object, path)Write bytes to file relative to build directory. Returns java.io.File.
karate.toAbsolutePath(path)Get absolute OS path. Handles prefixes like classpath:.
karate.toJavaFile(path)Get java.io.File instance for Java interop.

Read files as raw strings when you need to process content before parsing, and resolve classpath references to absolute OS paths. Use karate.write() to save response data to the build directory:

Gherkin
Feature: File operations

Scenario: Read and process files
* def schema = karate.readAsString('classpath:schemas/user.json')
* def absolutePath = karate.toAbsolutePath('classpath:data/test.csv')
* karate.log('File path:', absolutePath)

Scenario: Write response to file
Given url 'https://jsonplaceholder.typicode.com'
And path 'users', 1
When method get
Then status 200
* def file = karate.write(responseBytes, 'user-response.json')
* karate.log('Wrote to:', file.getPath())

HTTP and Network

Access HTTP request/response details and make programmatic HTTP calls.

MethodDescription
karate.call(fileName, [arg])Invoke feature file or JS function with optional argument.
karate.callSingle(fileName, [arg])Like call() but runs only once across all features.
karate.http(url)Return HTTP request builder for advanced use cases.
karate.prevRequestAccess actual HTTP request after execution.
karate.requestLast HTTP request as JS object. Use karate.request.header('name') for headers.
karate.responseLast HTTP response as JS object. Use karate.response.header('name') for case-insensitive header access.
karate.webSocket(url, [handler], [options])Create WebSocket for text messages.
karate.webSocketBinary(url, [handler], [options])Create WebSocket for binary messages.
karate.waitForHttp(url)Wait until URL accepts HTTP connections.
karate.waitForPort(host, port)Wait until host:port accepts socket connections.

Access response headers programmatically with case-insensitive lookup. Use karate.call() for conditional feature invocation based on response status:

Gherkin
Feature: HTTP access

Scenario: Access response headers case-insensitively
Given url 'https://httpbin.org'
And path 'get'
When method get
Then status 200
* def contentType = karate.response.header('content-type')
* match contentType contains 'application/json'

Scenario: Conditional feature call
Given url 'https://jsonplaceholder.typicode.com'
And path 'users', 1
When method get
* def userData = responseStatus == 200 ? response : karate.call('fallback-user.feature')
callSingle for Global Setup

Use karate.callSingle() in karate-config.js for expensive one-time setup like authentication tokens. The result is cached across all features.

Data Conversion

Convert between data formats and inspect types. For deep copying objects, use the copy keyword (not a karate method): * copy clone = original.

MethodDescription
karate.fromString(string)Convert string to JSON or XML based on content.
karate.toBean(json, className)Convert JSON to Java object given class name.
karate.toCsv(list)Convert JSON array to CSV string.
karate.toJava(function)Convert JS function for Java interop, or JSON to Java List/Map.
karate.toJson(object, [stripNulls])Convert Java object to JSON. Pass true to strip null values.
karate.toMap(object)Convert JSON to Java Map for driver config or Java interop.
karate.typeOf(any)Get type: null, boolean, number, string, list, map, function, xml.
karate.pretty(value)Pretty-print JSON value.
karate.prettyXml(value)Pretty-print XML value.
Gherkin
Feature: Data conversion

Scenario: Deep copy to prevent reference issues
* def original = { name: 'John', scores: [85, 90, 95] }
* copy clone = original
* set clone.scores[0] = 100
* match original.scores[0] == 85
* match clone.scores[0] == 100

Scenario: Type checking for dynamic data
* def data = { id: 1, name: 'Test' }
* match karate.typeOf(data) == 'map'
* match karate.typeOf(data.id) == 'number'
* match karate.typeOf(data.name) == 'string'
* match karate.typeOf(data.missing) == 'null'

Path Operations

Query JSON and XML using path expressions, and extract text with regex.

MethodDescription
karate.jsonPath(json, expression)Evaluate JsonPath in JavaScript.
karate.xmlPath(xml, expression)Evaluate XPath with dynamic expressions.
karate.extract(text, regex, group)Extract text using regex. Group follows Java regex rules.
karate.extractAll(text, regex, group)Extract all matches as array.

Use karate.jsonPath() to build dynamic filter expressions at runtime by concatenating variables into the path string. Use karate.extract() with regex capture groups to pull values from unstructured text:

Gherkin
Feature: Path operations

Scenario: Dynamic JsonPath queries
Given url 'https://jsonplaceholder.typicode.com'
And path 'users'
When method get
Then status 200
* def targetName = 'Bret'
* def user = karate.jsonPath(response, "$[?(@.username=='" + targetName + "')]")[0]
* match user.username == 'Bret'

Scenario: Extract text with regex
* def html = '<div class="price">$49.99</div>'
* def price = karate.extract(html, '\\$([0-9.]+)', 1)
* match price == '49.99'

System and Environment

Access system properties, environment info, and execute commands.

MethodDescription
karate.envCurrent environment from -Dkarate.env. Returns null if not set.
karate.osOS info object with name and type (windows, macosx, linux, unknown).
karate.properties[key]Read Java system property by name (e.g., -Dmy.port=8080).
karate.systemTimeCurrent timestamp in milliseconds (epoch time).
karate.exec(command)Execute OS command and return output string. Blocks until complete.
karate.fork(options)Fork OS process without blocking. Returns Command object with close() method.

Read system properties passed via -D flags (e.g., -Dapi.port=8080). Use karate.fork() to start a background process and karate.waitForHttp() to wait until it's ready:

Gherkin
Feature: System integration

Background:
* def port = karate.properties['api.port']
* def host = karate.properties['api.host']
* def env = karate.env

Scenario: Environment-specific configuration
* karate.log('Running in environment:', env)
* karate.log('OS type:', karate.os.type)
* def isWindows = karate.os.type == 'windows'

Scenario: Fork background process
* def proc = karate.fork({ args: ['node', 'server.js'] })
* karate.waitForHttp('http://localhost:3000')
# ... run tests ...
* proc.close()

Testing Utilities

Match validation, image comparison, logging, and configuration.

MethodDescription
karate.match(expression)Fuzzy match in JavaScript. Pass a full expression string like "response contains { id: '#number' }". Returns { pass: boolean, message: string }.
karate.compareImage(baseline, latest, [options])Compare images. Returns comparison results object.
karate.eval(expression)Evaluate dynamically generated JavaScript at runtime.
karate.configure(key, value)Same as configure keyword. Example: karate.configure('connectTimeout', 5000)
karate.log(...args)Log to Karate logger. Respects configure printEnabled.
karate.logger.debug(...args)Direct debug logging for CI/CD pipelines.

Use karate.match() with a string expression for programmatic validation. The string must be a complete match statement (e.g., "response contains { ... }"). Returns an object with pass (boolean) and message (error details):

Gherkin
Feature: Testing utilities

Scenario: Programmatic match validation
Given url 'https://jsonplaceholder.typicode.com'
And path 'users', 1
When method get
Then status 200
* def result = karate.match("response contains { id: '#number', name: '#string' }")
* if (!result.pass) karate.fail(result.message)

Metadata and Reporting

Access test metadata and embed content in reports.

MethodDescription
karate.featureCurrent feature metadata.
karate.scenarioCurrent scenario metadata including name.
karate.scenarioOutlineCurrent scenario outline metadata.
karate.tagsTags for current scope.
karate.tagValuesTag values in @name=val format.
karate.doc(arg)Render HTML and insert into report.
karate.render(arg)Render HTML template.
karate.embed(object, mimeType)Embed object/image into JSON report.
Gherkin
Feature: Test metadata

Scenario: Access scenario information
* karate.log('Feature:', karate.feature.name)
* karate.log('Scenario:', karate.scenario.name)
* def tags = karate.tags
* karate.log('Tags:', tags)

Setup Methods

For dynamic scenario outlines with @setup tag.

MethodDescription
karate.setup([name])Call scenario tagged with @setup. Returns all variables from setup.
karate.setupOnce([name])Like setup() but cached to run only once per feature.

See Dynamic Scenarios for detailed examples.

Encoding Utilities

URL encoding and XML handling.

MethodDescription
karate.urlEncode(string)URL encode string.
karate.urlDecode(string)URL decode string.
karate.setXml(name, xmlString)Set XML variable from string.

Encode special characters for use in URLs, or decode URL-encoded strings back to their original form:

Gherkin
Feature: Encoding utilities

Scenario: URL encode query parameters
* def searchTerm = 'hello world & special=chars'
* def encoded = karate.urlEncode(searchTerm)
* match encoded == 'hello+world+%26+special%3Dchars'
* def decoded = karate.urlDecode(encoded)
* match decoded == searchTerm

Scenario: Set XML from dynamic string
* def xmlString = '<user><name>John</name><id>123</id></user>'
* karate.setXml('userData', xmlString)
* match userData/user/name == 'John'
* match userData/user/id == '123'

Mock Server Methods

For use in Karate mock server scenarios. These methods are typically used in mock feature files that define stub responses or act as proxies to real servers.

MethodDescription
karate.proceed(url)Forward request to actual server in proxy mode. Returns response.
karate.start()Start mock server from within a test.
karate.target(object)For web UI automation target lifecycle.

Use karate.proceed() in mock scenarios to selectively forward requests to a real backend while intercepting specific endpoints:

Gherkin
Feature: Mock server with proxy

Background:
* def realBackend = 'https://jsonplaceholder.typicode.com'

Scenario: pathMatches('/users/{id}')
# Intercept user requests and return mock data
* def responseStatus = 200
* def response = { id: '#(pathParams.id)', name: 'Mock User', mock: true }

Scenario: pathMatches('/posts')
# Forward to real backend for posts
* karate.proceed(realBackend)

Scenario:
# Default: forward all other requests to real backend
* karate.proceed(realBackend)
Mock Documentation

For comprehensive mock server setup and usage, see the Karate Netty documentation. Mock servers are defined as feature files with special Scenario patterns.

Next Steps