4

I have a javascript file I want to call. contents are below. When I tried calling the file, I keep getting a "no variable found with name: response" even though there is clearly a variable defined. The file executes fine within command-line using node so the javascript function is valid. Any thoughts? I attached the error message in a screenshot.

Javascript content in snippet below.

Karate script:

Scenario: Call JavaScript:

    * def sample = read('classpath:reusable/gen-data.js')

    * print someValue

function createTestData(sampleJson, fieldsToChange, numRecords) {
    var testData = [];

    for (var i = 0; i < numRecords; i++) {
        var copy = JSON.parse(JSON.stringify(sampleJson));

        fieldsToChange.forEach(function(fieldToChange) {
            copy[fieldToChange] = copy[fieldToChange] + i;
        });

        testData.push(copy);
    }



    return {content: testData};
}

var testData = {

  "country": "US",
  "taskStatusCode" : "Closed",
  "facilityCode" : "US_203532",

};

function getTestData() {

  String testData = JSON.stringify(createTestData(testData, ["taskStatusCode", "facilityCode"], 1), null, 1);

  console.log("all done getTestData()");
  console.log("test data: \n" + testData);

  return testData;
};


console.log("calling getTestData()");
getTestData();

enter image description here

Lincoln88
  • 213
  • 5
  • 19
  • sorry, I can't help here as this is all very confusing. I have to say you seem to be un-necessary complicating things with JS. don't use JS unless you really truly have to. all the best. – Peter Thomas Oct 25 '17 at 02:43
  • I truly had to use JS in the above scenario. Ended up switching to java and worked like a charm. – Lincoln88 Feb 02 '19 at 11:48

2 Answers2

4

I think this error is thrown when the JavaScript is not correct. For example in my case this JS file:

/* Set the custom authentication header */
function fn() {
    var authToken = karate.get('authToken');
    var out = {};
    out['Auth-Token'] = authToken
    return out;
}

This file will produce the "no variable found with name: response".

The reason is because "the right-hand-side (or contents of the *.js file if applicable) should begin with the function keyword." according to the karate docs (link).

Now by moving the comment and making the function keyword the first bit of text it works as expected:

function fn() {
/* Set the custom authentication header */
    var authToken = karate.get('authToken');
    var out = {};
    out['Auth-Token'] = authToken
    return out;
}

In the OP, the function keyword is the first thing in the file, but there is javascript outside the original function -- which I don't think is legal for karate syntax. In other words, everything has to be in the outer function.

Kelly Summerlin
  • 651
  • 4
  • 10
0

My workaround was to use java instead of JavaScript.

Lincoln88
  • 213
  • 5
  • 19