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) | Create WebSocket connection |
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.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.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 | Get karate.env system property value (read-only) |
karate.properties[key] | Get any Java system property by name |
karate.os | Get OS details as JSON: { type: 'macosx', name: 'Mac OS X' } |
karate.exec(command) | Execute OS command and return output. Blocks until complete |
karate.fork(map) | 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)
```gherkin
### Conditional Logic
```gherkin
# 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')
```gherkin
### File Operations
```gherkin
# 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')
```gherkin
### Advanced Testing
```javascript
// 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)
```gherkin
### System Integration
```gherkin
# 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()
```gherkin
## Best Practices
### Performance
- Use `karate.callSingle()` for expensive setup operations
- Cache results when possible
- Use `karate.abort()` early to skip unnecessary processing
### Error Handling
```javascript
// 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'
```gherkin
### Debugging
```gherkin
# 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)
```gherkin
## Next Steps
- Review [Conditional Logic](/docs/advanced/conditional-logic) for control flow patterns
- Explore [Hooks and Lifecycle](/docs/advanced/hooks) for test setup
- Learn about [Java API](/docs/advanced/java-api) for Java integration