12 Karate Config.js - biswajitsundara/Karate GitHub Wiki
Karate configuration file is a key component in Karate framework. Its basically used for the below purpose.
- Stores global variables : Means any variable declared or initialized in this file can be accessed by any feature file directly.
- Configure url,proxy, authorization token
- Dynamically change the variable values based on environment (url value is often changed)
- This file is called by default, no need to call this in any way
- Remember the variables in karate config.js get
initialized/re initialized
after every feature file. If we need to assign values only once then we need to use callSingle.
Keep the file at this location src/test/java
function frameworkConfig() { var env = karate.env; // get system property 'karate.env' var os = karate.os; karate.log('karate.env system property was:', env); karate.log("your OS is:",os); if (!env) { env = 'dev'; } var config = { env: env, baseUrl: 'http://localhost:8080', os : os } if (env == 'dev') { config.baseUrl = 'http://localhost:8080/api' } else if (env == 'qa') { config.baseUrl = 'https://reqres.in'; } else if (env == 'qc') { config.baseUrl = 'http://dummy.restapiexample.com/'; } else if (env == 'prod') { karate.abort(); } return config; }
Feature: Test Karate Config Background: * url baseUrl Scenario: Read the variable from karate config Given path '/api/v1/create' And print baseUrl
package tests.config; import org.junit.BeforeClass; import org.junit.runner.RunWith; import com.intuit.karate.KarateOptions; import com.intuit.karate.junit4.Karate; @RunWith(Karate.class) @KarateOptions(features = "classpath:tests/config/ConfigTest.feature") public class ConfigTestRunner { @BeforeClass public static void before() { System.setProperty("karate.env", "qa"); } }
Lets say we have one common authorization scheme across feature files. Then we can have the authorization token generated in one feature file and then use it across. We will have to use callSingle
if the requirement is to generate the authrozation token only once.
//Changes in karate-config.js file //We can pass argument to the feature file also (just put a comma and add parameter ('classpath:..',parameter) var result = karate.callSingle('classpath:tests/authorization/UserAuthentication.feature'); config.authInfo = result config.auth = {accessToken:result.accessToken} return config; //Feature file And print authInfo And print authInfo.accessToken And print authDirectly use config.authInfo etc and that will add the field authInfo to the existing config object.