4

Description : Getting reference error message after upgrading to karate 1.1.0.RC3

Steps: Execute the test.feature file

test.feature

  Scenario: Get custom request
    * def testUtils = call read('classpath:features/utils.feature')
    * def getRequest = testUtils.customRequest()
    * print getRequest 

Utils.feature

Feature: common utilities

  Scenario: 
    * def randomAlphabetic = function (count) { return org.apache.commons.lang3.RandomStringUtils.randomAlphabetic(count) }

    * def customRequest =
    """
     function() {
     var name = randomAlphabetic(2)
     return {
         name:name,
         city:'Bangalore'
     }
  }
    """

Error message :

org.graalvm.polyglot.PolyglotException: ReferenceError: "randomAlphabetic" is not defined
- <js>.:anonymous(Unnamed:2)

Git repo for reference - https://github.com/naveenkrao/karate-sample-project

naveenkrao
  • 41
  • 1
  • 3

1 Answers1

1

There are some limits to re-use of JS functions in the new versions. There are multiple work-arounds. Here is one below, to move the re-usable function within the JS block itself:

* def customRequest =
"""
 function() {
 var randomAlphabetic = function (count) { return java.lang.System.currentTimeMillis() + '' };
 var name = randomAlphabetic(2);
 return {
     name:name,
     city:'Bangalore'
 }
}
"""

Or if you make the randomAlphabetic function globally available e.g. via karate-config.js it may also work.

This is a consequence of the JS engine change which we tried hard to address. You are most welcome to contribute code if this is a problem for you. We think not, there are many ways to create re-usable functions, follow some rules - keep them simple, prefer Java for complex logic, and don't mix or compose JS or Java too much.

You are also welcome to contribute documentation if you feel that it needs to be updated.

Peter Thomas
  • 54,465
  • 21
  • 84
  • 248