cucumbercypressfeature-file

How to add a Before() function in Cypress Feature Files?


I am using feature files in my Cypress framework.

Below is an example of a scenario:

Scenario: #1 Cancel should return to Customer Management landing page
 Given User is on the Edit Customer Page
 When User updates the email address to "abc@gmail.com"
 Then the updated email address will appear on the summary page

The problem I'm facing is that when I re-run this test, the original email address will be "abc@gmail.com" (the value it was updated to during the first test run). So the test won't actually update the email address.

What is the best approach to deal with this issue?

I was thinking of using something like a Before() function to delete the customer if it exists, & re-create it. Then I'd be able to update it & the values will be the same each time.

However, I don't know how to add a Before() in a feature file. I have a Background that navigates to a certain page, but is that the place where I should be putting it?


Solution

  • The cypress-cucumber-preprocessor supports both Mocha's before/beforeEach/after/afterEach hooks and Cucumber's Before and After hooks. So in your step Definition file, you can:

    //This example is with the Cucumber hooks
    const {
      Before,
      After,
      Given,
      Then,
    } = require('cypress-cucumber-preprocessor/steps')
    
    // this will get called before each scenario
    Before(() => {
      //Code to delete customer if it exists
    })