问题
- karate-config.js has
config = karate.callSingle('classpath:token-read.js', config);
- Javascript function on token-read.js is
function fn(config) {
var userAccessToken = Java.type("com.OAuth2Token");
config['OAuth2'] = {
adminUser: function () {
return userAccessToken.getAuthorizationHeader(name, url, users, "ADMIN");
},
};
return config;
}
- Feature file code is as below
Feature: Search data
Scenario: Sample
Given url url
Given path '/data'
And header Authorization = OAuth2.adminUser() // Using javascript fun here
And param request = {"up":10}
And print response
When method GET
Then status 200
- Getting error
javascript evaluation failed: OAuth2.adminUser(), TypeError: OAuth2.adminUser is not a function in <eval> at line number 1
Above feature file is working fine with karate 0.9.2 , but not working with 0.9.3
回答1:
Please read this section of the docs: https://github.com/intuit/karate/tree/develop#restrictions-on-global-variables
Reproducing here:
Non-JSON values such as Java object references or JS functions are supported only if they are at the "root" of the JSON returned from karate-config.js. So this below will not work:
function fn() {
var config = {};
config.utils = {};
config.utils.uuid = function(){ return java.util.UUID.randomUUID() + '' };
// this is wrong, the "nested" uuid will be lost
return config;
}
The recommended best-practice is to move the uuid function into a common feature file following the pattern described here:
function fn() {
var config = {};
config.utils = karate.call('utils.feature')
return config;
}
But you can opt for using karate.toMap() which will "wrap" things so that the nested objects are not "lost":
function fn() {
var config = {};
var utils = {};
utils.uuid = function(){ return java.util.UUID.randomUUID() + '' };
config.utils = karate.toMap(utils);
return config;
}
You may need to upgrade to 0.9.5.RC4 for some of this to work, so do try.
来源:https://stackoverflow.com/questions/59038178/migration-form-karate-0-9-2-to-0-9-3-issue-javascript-evaluation-failed