Search code examples
datatablecucumbercypress

How to get value from datatables to loop through multiple test scenarios?


I am trying to use datatables to loop through multiple scenarios, but my step definitions are not getting the values from the datatables

Feature file:


  Scenario Outline: Try login with invalid <username> and <password> should throw an error <message>
  Given I am on the login screen.
  When I login with a <username> and <password>
  Then the system should throw a relevant error <message>
  Example: 
          | username                      | password        | message                     |
          | aminster                      | test@12         | Invalid Login. Try again.   |
          | s                             | 3               | Invalid Login. Try again.   |

I want to validate the error on the login screen for invalid data with multiple scenarios

Below is my step definition

Given("I am on the login screen.", () => {
  cy.visit("https://demotest.com/login#login");
  cy.wait(1000);
});

When(/^I login with a (.+) and (.+)$/, (username, password) => {
    cy.get('input[id="login_email"]').type(username);
    cy.get('input[id="login_password"]').type(password);
    cy.get('button[type="submit"]').eq(0).click();
    cy.wait(5000);
});

Then(/^the system should throw a relevant error (.+)$/, (message) => {
  cy.get('button[type="submit"]').eq(0).should('include', message)
})

But not able to get values of username, password and message from the datatable.


Solution

  • Your feature file and step-definition needs to be updated in order to make the Scenario Outline work.

    1. should be "Examples" not "Example"
    2. enclose the values with double quote '"' in the examples table feature file and update the step definition file to just simply capture as string, no need to use regex.

    Feature File:

        Scenario Outline: Try login with invalid <username> and <password> should throw an error <message>
           Given I am on the login screen.
           When I login with a <username> and <password>
           Then the system should throw a relevant error <message>
           Examples:
               | username   | password  | message                     |
               | "aminster" | "test@12" | "Invalid Login. Try again." |
               | "s"        | "3"       | "Invalid Login. Try again." |
    

    Step Definition File:

    Given("I am on the login screen.", () => {
      cy.visit("https://demotest.com/login#login");
      cy.wait(1000);
    });
    
    When("I login with a {string} and {string}", (username, password) => {
        cy.get('input[id="login_email"]').type(username);
        cy.get('input[id="login_password"]').type(password);
        cy.get('button[type="submit"]').eq(0).click();
        cy.wait(5000);
    });
    
    Then("the system should throw a relevant error {string}", (message) => {
      cy.get('button[type="submit"]').eq(0).should('include', message)
    })