One can read file using the built-in JavaScript function called read() in karate.By default, the file is expected to be in the same folder (package) and in parallel with a *.feature file. But you can prefix the name with classpath: in this case the “root” folder will be src//test/java If a file does not end in .json, .xml, .yaml, .js, .csv or .txt, it is treated as a stream – which is typically what you would need for multipart file uploads.
You can read different types of files using the read function.
# json * def someJson = read('some-json.json') * def moreJson = read('classpath:more-json.json') # Grapql file * Given def query = read('createEmployerQuery.graphql') * Given def variables = read('createEmployerVariable.graphql') # javascript (will be evaluated) * def someValue = read('some-js-code.js') # if the js file evaluates to a function, it can be re-used later using the 'call' keyword * def someFunction = read('classpath:some-reusable-code.js') * def someCallResult = call someFunction # perfect for all those common authentication or 'set up' flows * def result = call read('classpath:some-reusable-steps.feature')
We will now see a example of how a feature will read a Graphql file within the same package.
Feature: Reading a external file in a karate feature file Background: * url AppURL #refer karate-config.js to see how these were initialized * header Authorization = 'Bearer ' + token Scenario: Create all employer details #We are reading two files here, one us Mutation query Given def query = read('createEmployerQuery.graphql') # Below file is the graphql variable file Given def variables =read('createEmployerVariable.graphql') #And def variables = { name: 'Charmander' } And request { query: '#(query)', variables: '#(variables)' } #And request { query: '#(query)' } When method post * print response Then status 200
If you can trying to read a file placed outside of the feature file package and can specify the path using “classpath”.
Given def variables =read('classpath:packageName/folderName/createEmployerVariable.graphql')