sample.feature
Scenario Outline: My test case
Given: My data is loaded
When : My data is ready
Then: My data is
|name| value |
|a | <value1> |
|b | <value2> |
|c | <value3> |
|d | <value4> |
Examples:
|value1| value2|value3| value4 |
|1 | 2 | 3 | text |
steps.js //using node.js
Then('My data is', function (dataTable) {
console.log(dataTable);
// console output
[['a', '1'],
['b', '2'],
['c', '3'],
['d', 'text']]
});
I need output as string value as string and Integer as Integer
// expected output
[['a', 1],
['b', 2],
['c', 3],
['d', 'text']]
I don't want to hardcode based on name, because It may change. Is there a generic solution available?
You can detect if a value is numeric or not using isNaN(x)
. If the isNaN(x)
function returns false
, you can safely ignore that value in the cucumber data table. If the isNaN(x)
function returns true
then you can use the Number(x)
function to convert the string to a number.
The isNaN
and Number
functions are complimentary. For any given input, if isNaN
returns true
, then passing that same input to Number
will return a NaN
value. If isNaN
returns false
then passing that input to Number
will successfully convert it to a Number.
Remember that zero is a falsey value in JavaScript, so if (Number("0"))
will be evaluate to false
.
function parseDataTable(dataTable) {
return dataTable.map((row, index) => {
if (!isNaN(row[1])) {
row[1] = Number(row[1]);
}
return row;
});
}
And to use it in your step definition:
Then('My data is', function (dataTable) {
dataTable = parseDataTable(dataTable);
console.log(dataTable);
/*
Should output:
[
["a", 1],
["b", 2],
["c", 3],
["d", "text"]
]
*/
});