ADVANCED
Karate Object API
The karate
object is a powerful utility available at runtime in JavaScript functions and Karate expressions, providing methods for test control, data manipulation, and advanced testing scenarios.
Overview
The karate
object is automatically available in:
- JavaScript functions within feature files
- Karate expressions
- karate-config.js
- called JavaScript files
API Reference
Test Control Methods
Method | Description |
---|---|
karate.abort() | Prematurely exit a Scenario. Use with conditional logic: * if (condition) karate.abort() . Use sparingly to avoid non-deterministic tests. |
karate.fail(message) | Conditionally stop a test with a descriptive error message: * if (condition) karate.fail('Expected something else') |
karate.pause(number) | Sleep time in milliseconds. Relevant for performance testing, no-op otherwise unless configure pauseIfNotPerf is true |
karate.stop(port) | Pause test execution until a socket connection is made to the specified port. Useful for debugging UI tests. NEVER forget to remove after use! |
karate.signal(result) | Trigger an event that karate.listen(timeout) is waiting for. See async operations. |
Data Manipulation
Method | Description |
---|---|
karate.append(...items) | Create lists from items (which can be lists as well). Useful for JSON transforms. |
karate.appendTo(name, ...items) | Append to an existing list-like variable. First argument can be a reference or variable name (string). |
karate.distinct(list) | Returns only unique items from an array of strings or numbers |
karate.filter(list, predicate) | Functional filter operation. Second argument must be a JS function (item, [index]) returning boolean |
karate.filterKeys(map, keys) | Extract subset of key-value pairs. Second argument can be a list of keys or another JSON object |
karate.forEach(list, function) | Functional loop operation. Function signature: (item, [index]) for lists, (key, [value], [index]) for maps |
karate.keysOf(object) | Returns only the keys of a map-like object |
karate.lowerCase(object) | Convert all keys and values in JSON or XML to lowercase |
karate.map(list, function) | Functional map operation. Second argument must be a JS function (item, [index]) |
karate.mapWithKey(list, string) | Transform array of primitives into array of objects |
karate.merge(...maps) | Merge key-values of two or more JSON/map objects |
karate.range(start, end, [interval]) | Returns JSON array of integers (inclusive). Optional interval defaults to 1 |
karate.repeat(count, function) | Build array with count items or execute function count times |
karate.sizeOf(object) | Returns size of map-like or list-like object |
karate.sort(list, function) | Sort list using custom function. Example: karate.sort(myList, x => x.val) |
karate.valuesOf(object) | Returns only values of a map-like object |
Variable Management
Method | Description |
---|---|
karate.get(name, [default]) | Get variable value by name or JsonPath. Returns null if not found. Optional default value. |
karate.set(name, value) | Set variable value immediately. Useful when other routines depend on that variable |
karate.set(object) | Set multiple variables from Map or JSON in one operation |
karate.set(name, path, value) | Conditionally build payload elements, especially XML |
karate.remove(name, path) | Conditional removal of JSON keys or XML nodes |
File Operations
Method | Description |
---|---|
karate.read(filename) | Read file (same as global read() function) |
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 reference |
karate.toAbsolutePath(relativePath) | Get absolute OS path, handles prefixes like classpath: |
karate.toJavaFile(path) | Get java.io.File instance for Java interop |
HTTP and Network
Method | Description |
---|---|
karate.call(fileName, [arg]) | Invoke feature file or JavaScript function with optional argument |
karate.callSingle(fileName, [arg]) | Like call() but guaranteed to run only once across features |
karate.http(url) | Returns Http request builder class for advanced use |
karate.prevRequest | Access actual HTTP request after execution |
karate.request | Access last HTTP request as JS object. Example: karate.request.header('some-header') |
karate.response | Access last HTTP response as JS object. Example: karate.response.header('some-header') |
karate.webSocket(url, [handler], [options]) | Create WebSocket connection for text messages |
karate.webSocketBinary(url, [handler], [options]) | Create WebSocket connection for binary messages (byte arrays) |
karate.waitForHttp(url) | Wait until URL accepts HTTP connections |
karate.waitForPort(host, port) | Wait until host:port accepts socket connections |
Data Conversion
Method | Description |
---|---|
karate.copy(object) | Deep copy JSON or XML objects (prevents pass-by-reference issues) |
karate.fromString(string) | Convert dynamic 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 object to Java Map for driver config or Java interop |
karate.typeOf(any) | Get type for dynamic conditional logic |
karate.pretty(value) | Pretty-print JSON value |
karate.prettyXml(value) | Pretty-print XML value |
Path Operations
Method | Description |
---|---|
karate.jsonPath(json, expression) | JsonPath evaluation in JavaScript |
karate.xmlPath(xml, expression) | XPath evaluation with dynamic expressions |
karate.extract(text, regex, group) | Extract text from non-JSON/XML sources like HTML |
karate.extractAll(text, regex, group) | Extract all text matches as list |
System and Environment
Method | Description |
---|---|
karate.env | Current environment name (set via -Dkarate.env) |
karate.os | OS info. Returns object with name and type (windows, macosx, unix) |
karate.properties[key] | Read Java system property by name (e.g., -Dmy.port=8080) |
karate.systemTime | Current timestamp in milliseconds (epoch time) |
karate.exec(command) | Execute OS command and return output string |
karate.fork(options) | Fork OS process in parallel without blocking. Returns Command object |
Testing Utilities
Method | Description |
---|---|
karate.match(actual, expected) | Fuzzy match in JavaScript. 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 |
Advanced Features
Method | Description |
---|---|
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 |
karate.feature | Get metadata about current feature |
karate.scenario | Get metadata about current scenario |
karate.scenarioOutline | Get metadata about current scenario outline |
karate.tags | Get tags for current scope |
karate.tagValues | Get tag values in @name=val format |
karate.setup([name]) | Call scenario tagged with @setup |
karate.setupOnce([name]) | Like setup() but cached to run only once |
karate.start() | Start mock server from within test |
karate.target(object) | For web UI automation target lifecycle |
Encoding Utilities
Method | Description |
---|---|
karate.urlEncode(string) | URL encode string |
karate.urlDecode(string) | URL decode string |
karate.setXml(name, xmlString) | Set XML from string |
Usage Examples
Data Manipulation
// Filter and transform arrays
* def users = karate.filter(userList, x => x.age > 18)
* def names = karate.map(users, x => x.name)
* def unique = karate.distinct(names)
// Merge objects
* def combined = karate.merge(defaults, overrides, customSettings)
// Sort with custom function
* def sorted = karate.sort(items, x => x.priority)
// Generate unique IDs
* def orderId = karate.uuid()
* def correlationId = karate.uuid()
Object Copying
# Deep copy to prevent pass-by-reference issues
* def original = { name: 'John', scores: [85, 90, 95] }
* def copy = karate.copy(original)
* set copy.scores[0] = 100
# Original is unchanged
* match original.scores[0] == 85
* match copy.scores[0] == 100
# Without copy, changes affect both references
* def sharedRef = original
* set sharedRef.name = 'Jane'
* match original.name == 'Jane'
Conditional Logic
# Abort on condition
* if (response.status != 'ready') karate.abort()
# Fail with message
* if (!response.data) karate.fail('No data received')
# Dynamic type checking
* def type = karate.typeOf(response)
* if (type != 'json') karate.fail('Expected JSON response')
File Operations
# Read and write files
* def data = karate.read('data.json')
* def result = processData(data)
* def file = karate.write(result, 'output.json')
* print 'Wrote to:', file.getPath()
# Get absolute paths
* def fullPath = karate.toAbsolutePath('classpath:data/test.csv')
Advanced Testing
// Compare images
* def result = karate.compareImage('baseline.png', 'current.png')
* if (result.mismatchPercentage > 5) karate.fail('Images differ by ' + result.mismatchPercentage + '%')
// Dynamic evaluation
* def code = "function() { return 'dynamic-' + new Date().getTime(); }"
* def result = karate.eval(code)
// Match validation
* def validation = karate.match(response, expected)
* if (!validation.pass) karate.fail(validation.message)
System Integration
# Execute system commands
* def output = karate.exec('echo "Hello World"')
* print output
# Fork background process
* def proc = karate.fork({ args: ['node', 'server.js'] })
* karate.waitForHttp('http://localhost:3000')
* proc.close()
System Properties
# Read system properties passed via -D flags
# Run with: mvn test -Dapi.port=8080 -Dapi.host=staging.example.com
Background:
* def port = karate.properties['api.port']
* def host = karate.properties['api.host']
* def baseUrl = 'http://' + host + ':' + port
Scenario: Dynamic configuration
Given url baseUrl
And path 'status'
When method get
Then status 200
# Useful for dynamic port numbers in embedded servers
* def serverPort = karate.properties['server.port']
* def apiUrl = 'http://localhost:' + serverPort + '/api'
WebSocket Operations
# Text WebSocket connection
* def socket = karate.webSocket('ws://echo.websocket.org')
* socket.send('Hello WebSocket')
* listen 5000
* match listenResult == 'Hello WebSocket'
# Binary WebSocket for file transfers
* def binarySocket = karate.webSocketBinary('ws://localhost:8080/upload')
* bytes imageData = read('test-image.png')
* binarySocket.send(imageData)
* listen 10000
* bytes response = listenResult
* match response.length > 0
# WebSocket with authentication
* def token = 'Bearer eyJhbGc...'
* def options = { headers: { Authorization: token }, maxPayloadSize: 8388608 }
* def authSocket = karate.webSocket('wss://api.example.com/stream', null, options)
Proxy Mode and Mock Servers
# Selective request interception in mock server
# karate.proceed() forwards request to actual server
Background:
* def demoServer = 'https://api.example.com'
Scenario: pathMatches('/api/users/{id}') && methodIs('get')
# Intercept specific GET requests, proxy everything else
* def userId = pathParams.id
# For admin user, return mock data
* if (userId == '1') karate.abort()
* def response = { id: 1, name: 'Admin User', role: 'admin' }
# For other users, proxy to real server
* def response = karate.proceed(demoServer)
Scenario: pathMatches('/api/orders')
# Always proxy orders endpoint to real server
* def response = karate.proceed(demoServer)
# But modify response before returning
* set response.mockedBy = 'Karate'
Best Practices
Performance
- Use
karate.callSingle()
for expensive setup operations - Cache results when possible
- Use
karate.abort()
early to skip unnecessary processing
Error Handling
// Defensive programming
* def value = karate.get('optionalVar', 'defaultValue')
* if (!value) karate.fail('Required value not found')
// Type safety
* def type = karate.typeOf(data)
* match type == 'json'
Debugging
# Debug helpers
* karate.log('Debug info:', response)
* karate.logger.debug('Detailed trace:', karate.pretty(complexObject))
# Pause for debugging
* if (karate.env == 'debug') karate.stop(9515)
Next Steps
- Test WebSocket connections: WebSocket Testing
- Handle async operations: Polling and Async
- Review conditional logic: Conditional Logic
- Set up test hooks: Hooks and Lifecycle
- Java integration: Java API