How to pass data from the feature file to step definition file using regular expressions?

16,374

I would try changing the regular expression in your JavaScript to a string that expects the variables you're passing into the Given statement:

Given('I open the page with the url {string}'), function(next) {
  //your code
}

You can define variables in the Gherkin Given statements by stating them as they would be presented typically. For example, if you wanted to pass in a string:

Scenario: 0 | A User Logging In
Given I open the page with the url "http://localhost"

Would pass in the variable url to your javascript file and contain the string http://localhost

Same goes for integers:

Scenario: 0 | A User Logging In
Given I open the page with the url "http://localhost" and port 3000

Your javascript function will now receive 2 variables, url and port. Logging them to the console, you will see

http://localhost
3000

So I would re-arrange your code to look like the following:

Gherkin:

Scenario: 0 | A User Logging In
Given I open the page with the url "http://localhost:3000/login"

JavaScript:

Given('I open the page with the url {string}', (url, next) => {
     console.log(url) // log to check the variable is being passed into the function

     driver.get(url);

     pageElement = driver.findElement(By.id("email"));
     pageElement.sendKeys("[email protected]");

     next(); 
});

EDIT: You can find all the documentation on this particular issue here.

Share:
16,374

Related videos on Youtube

Jack Williams
Author by

Jack Williams

Automation Engineer - Specializing in CucumberJS

Updated on June 04, 2022

Comments

  • Jack Williams
    Jack Williams almost 2 years

    This project is using NodeJS, Cucumber, Gherkin, Selenium.

    I am trying to pass either a stored value or for now, a value in this example it would be a URL from the feature file into the step definitions file through the usage of regular expressions.

    An example of a feature i would like to use (< url > is my guess-work which i've seen in other examples, which doesnt seem to work)

    Scenario: 0 | A User Logging In
    Given I open the page with the <url> 
    

    And then also my step definitions file

    Given("/^I open the page with the url? (.*)$/"), function(next){
    
        driver.get("http://localhost:3000/login");
        pageElement = driver.findElement(By.id("email"));
        pageElement.sendKeys("[email protected]");
        next(); 
    };
    

    I believe my step definitions file is correct however i'm not positive.

    If you need any more information about my project please let me know i am active throughout the day on stack-overflow and aim to have this working quickly.

    Thank you in advance for any support, Jack

  • Jack Williams
    Jack Williams over 5 years
    This is working, thank you for your help it is much appreciated @blueprintChris