How do I invoke my JS Function for a particular column in a csv file in the Karate Framework?

Viewed 82

I have a feature file that reads a csv file with multiple rows and I need to validate that if two of the columns meet certain conditions, the third column needs to be mandatory. I have tried using a js function however I am unsure as to how I should call this function for the third column. So based on the example below, if the name is Chicken, the unit kg then the cost needs to be mandatory.

#
noinspection CucumberTableInspection
Feature: Serverless

Scenario Outline: Per Row *
  def row =
  ""
" {
  name: '<Name>',
  unit: '<Unit>',
  cost: '<Cost>',
}
@FunctionComparison
  ""
" *
def name = '<Name>' *
  def unit = '<Unit>' *
  def cost = '<Cost>' *
  def checkMandatory =
  ""
"

function(arg1, arg2, arg3) {
  if (arg1 in ('Chicken')) {
    if (arg2 in ('kg')) {
      if (arg3.length < 0) {
      
        return false;
      }
      return true;
    }
    return true;
  }
  return true;
}


""
" *
match row ==
  ""
" {
  name: '#ignore',
  unit: '#regex ea|kg|ml',
  cost: 'checkMandatory(name, unit, cost) == true'

}
""
"
Examples:
  |
  read('input' + '.csv') |

The input.csv is simply a csv file with the following:

Line,Name,Unit,Cost (Columns)

1,Cheese,ea,34.50 2,Cake,ea,55.54 3,Chicken,kg, 4,Cement,ml,4.32

1 Answers

Your validation function can be a lot simpler, try this:

* def third = { name: 'foo', unit: 'bar', cost: '' }
* def isValid = function(x){ return (x.name && x.unit) ? x.cost.length != 0 : true }
* assert !isValid(third)

Note that Scenario Outlines will inject the variables, so there is no need for the < and > placeholders: https://github.com/intuit/karate#scenario-outline-enhancements

You can try this self-contained working example:

Feature:

Background:
* text data =
"""
name,unit,cost
Cheese,ea,34.50
Cake,ea,55.54
Chicken,kg,
Cement,ml,4.32
"""
* csv data = data
* def isValid = function(x){ return (x.name && x.unit) ? x.cost.length != 0 : true }

Scenario Outline:
* assert isValid(__row)

Examples:
| data |
Related