So, today I will give a code snippet about how to deal with Cucumber data tables and protractor.
Following the example:
- Scenario with data table:
Scenario: Register multiple users from different countries Given I want to register multiple users | user | country | | nicko | uk | | pitty | brazil | | slash | us | When I send the form Then all the users should be registered
Remember to create the data table with the headers. Don’t forget that data tables are different from examples, here the first step will create a hash table with the data from the table and send it as parameter. Examples are used to run the same scenario with different variables in each run.
- Related Step Definitions:
'use strict'; var protractor = require('protractor'); var browser = protractor.browser; var _ = require('lodash'); var Q = require('q'); var RegisterPageSteps = function() { this.Given(/^I want to register multiple users$/, function(data) { var promises = []; var rows = data.hashes(); //For each row you will get the user and the country _.each(rows, function(row) { var user = row.user; var country = row.country; //Here you can add the promises to perform sequentially //you can call the promises passing the user and the //country as parameters promises.push((addUserCountry(user, country)); }); //You can also have promises to be performed that don't need //the parameters from the data table promises.push(navigateToSubmit()); //Here you return all the promises return Q.all(promises); }); this.When(/^I send the form$/, function(callback) { callback(); }); this.Then(/^all the users should be registered$/, function(callback) { callback(); }); }; module.exports = RegisterPageSteps;
I have not implemented other functions and steps as the aim here is to show how to deal with the data table in your scenario.
Thank you !
Do you have an example where you compare the datatable to some values in the UI like a HTML table in the UI?
Do you mean compare the UI table element value to the examples in the table you have in the BDD scenario ?
yes, that’s correct.
I tried converting the UI html table to a 2D array and compare it to table.rows() as the table.rows() from cucumber BDD is a 2 D array as well. This approach failed because when I get values from the UI, the values get pushed into the array asynchronously and therefore the assertion fails as the order is not correct.
2nd approach: Tried getting the values of the UI in a single array with the index argument that comes as part of .each(). This worked but now , I am not able to flatten table.rows() from cucumber which is a 2D array to a single D array. Any ideas how I can achieve this?
For the first approach, have you tried to compare the arrays with contain so it wouldn’t matter the position of the values. Something like: