Patrick
Patrick

Reputation: 119

Using call read within a js function

I have a slight problem I want to solve. I have the following lines of code which create 2 users which works. However the issue is that, it creates both users with the same Id from the the first line of code:

So I want to be able to create multiple users with different Ids. I tried the following:

* def users =

    """
    function(){
        var myId = null;
        if(myId == null)
        {
          myId = call read('classpath:karate/helpers/guid.js')
        }
        karate.call('classpath:v1/api_CreateUser.feature');
    }
    """ 

So the idea is to reset the 'myId' variable everytime to null, check if null which will be true, then call the js function which generates the id and assign the result to 'myId' variable. Then the variable will be used on the karate.call('classpath:v1/api_CreateUser.feature') line.

Unfortunately I'm getting javascript evaluation failed error.

Anyone could help?

Thanks

Upvotes: 1

Views: 971

Answers (1)

Peter Thomas
Peter Thomas

Reputation: 58128

Be clear about the slight difference when you are in Karate and when you are in JS. For example:

myId = call read('classpath:karate/helpers/guid.js')

This won't work. What you are looking for is:

myId = karate.call('classpath:karate/helpers/guid.js');

I recommend you read and understand the section on Karate Expressions it will save you a lot of trouble later.

When you use a JS function (that works) you should never need to worry about what you are. Just invoke it wherever, and it will "dispense" a new value. For example if you have:

* def time = function(){ return java.lang.System.currentTimeMillis() + '' }
* def first = time()
* def second = time()

Here first and second will always be different. I think now you have all you need. You are trying to access a JS variable defined in Karate from within a function, this depends on when either was initialized and I don't recommend it if you don't know what you are doing. But if you want to access the latest value of a Karate variable, the right way is to use karate.get(varNameAsString).

Upvotes: 2

Related Questions