Is it possible to have multiple JS functions inside one JS file of karate framework?
Asked Answered
J

2

7

I need to perform two operations on the result of JSON responses.so can we have those different operations inside single JS file? or do we need to have mapping like one JS file for one operation. Please help on this

Johnny answered 20/3, 2018 at 10:36 Comment(0)
T
13

I don't recommend trying to create complicated JavaScript in Karate, it just leads to maintainability issues. If you really want an object with multiple utility methods on it, write a Java class with static methods, and it will be much easier to maintain / debug.

That said, if you really insist - look at this answer: https://mcmap.net/q/1476899/-how-to-call-a-particular-javascript-function-from-js-file-in-karate-feature-file

But this is what I recommend for most projects. In one "common" feature file, define multiple methods like this:

Scenario:
* def now = function(){ return java.lang.System.currentTimeMillis() }
* def uuid = function(){ return java.util.UUID.randomUUID() + '' }

You can now call this feature like this:

* call read('common.feature')

And now all the functions in that feature are available for use:

* def time = now()
* def id = uuid()
Thallium answered 20/3, 2018 at 12:53 Comment(1)
I find myself struggling with calling *.feature files and js in one go. In your example for common.feature is the entire file outlined like this? Background: * def now = function(){ return java.lang.System.currentTimeMillis() } * def uuid = function(){ return java.util.UUID.randomUUID() + '' }Adenovirus
J
5

@kmancusi This is how I did a common.feature file with my common functions and then the following my.test.feature shows how I import that to use it in another feature.

common.feature

@ignore
Feature:

Scenario:
  * def now = 
      """
        function() { 
          return java.lang.System.currentTimeMillis() 
        }
      """ 

  * def uuid = 
     """
       function() { 
         return java.util.UUID.randomUUID() + '' 
       }
     """

my.test.feature

Feature: my tests

Background:
  * configure logPrettyRequest = true
  * configure logPrettyResponse = true
  * configure ssl = true

Scenario: basic test

  * def util = call read('common.feature')
  * def sessionId = util.uuid()

  * print sessionId
Jurado answered 30/4, 2019 at 1:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.