You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesión a prueba de IA

Antes: $249

Currency
$209
Suscríbete

Termina en:

0 Días
10 Hrs
51 Min
4 Seg
Curso de Cypress Avanzado

Curso de Cypress Avanzado

Javier Fuentes Mora

Javier Fuentes Mora

Configuración de plugins y steps dinámicos

20/29
Resources

What is BDD and how does it integrate with Cypress?

Behavior Driven Development (BDD) is a methodology that improves software development by focusing on collaboration between developers, testers and non-programmers on a software project. One of the most popular tools for implementing BDD is Cucumber, which uses the Gherkin language to write user stories and automated tests. Although Cypress does not support Gherkin natively, it is possible to integrate it via plugins to improve testing efficiency.

How do I install the necessary libraries?

To integrate BDD in Cypress with Gherkin, we will install two essential libraries: Cypress Webpack Processor and Baitable Cypress Cucumber Prep Processor. These libraries allow Cypress to interpret and process the feature files properly.

npm install --save-dev @badeball/cypress-cucumber-preprocessornpm install--save-dev cypress-webpack-preprocessor

How to configure Cypress for BDD?

The Cypress configuration must be adjusted to use these newly installed libraries. A vital aspect is to adjust the cypress.config.js file to allow Cypress to recognize and use feature files as tests:

  1. Modifying node events: creating an asynchronous function to detach and import the necessary libraries.
  2. Adjusting the Webpack configuration: Use the Webpack plugin to transcribe the feature files into a format understandable by Cypress.
  3. Changing the spec pattern: Redefine the spec pattern so that Cypress uses .feature files instead of .cy files.
const { defineConfig } = require('cypress');constpreprocessor = require('@badeball/cypress-cucumber-preprocessor');
module.exports = defineConfig({ e2e: { setupNodeEvents(on, config) { await preprocessor.addCucumberPreprocessorPlugin(on, config); on('file:preprocessor', preprocessor.createBabelPreprocessor()); return config; }, specPattern: 'cypress/e2e/**/**/*.feature', },});

How do I structure tests in feature files?

It is vital to organize your test files properly. Inside the cypress/e2e directory, create a directory for your features called features, where you will store your test files written in Gherkin.

Feature: User login Scenario: Login with valid credentials Given I am on the login page When I enter a valid username and password Then I should see the homepage

How are dynamic steps created and configured?

The use of steps makes the tests clearer and more understandable. You can import functions such as Given, When, and Then from the preprocessor to define scenarios:

import { Given, When, Then } from '@badeball/cypress-cucumber-preprocessor';
Given('I am on the login page', () => { cy.visit('/login');});
When('I enter {string} and {string}', (username, password) => { cy.get('#username').type(username); cy.get('#password').type(password); cy.get('#login-button').click();});
Then('I should see the homepage', () => { cy.url().should('include', '/home');});

What are the advantages of the BDD approach in Cypress?

Implementing BDD in Cypress provides several significant advantages:

  • Readability and collaboration: The feature files are clear and anyone involved in the project, such as a Product Owner, can understand and, moreover, modify the tests without the need for advanced technical knowledge.
  • Reusable tests: Defined steps can be reused in different tests, which saves time and maintains consistency.
  • Increased flexibility: Thanks to dynamic steps, you can pass different parameters in the same step, without the need to create redundant lines of code for each scenario.

The integration of these principles and practices not only improves software quality, but also facilitates collaboration and communication within the development team. Get ready to implement BDD in your projects with Cypress!

Contributions 10

Questions 0

Sort by:

Want to see more contributions, questions and answers from the community?

La config de webpack.

webpack({
      webpackOptions: {
        resolve: {
          extensions: [".ts", ".js"],
        },
        module: {
          rules: [
            {
              test: /\.feature$/,
              use: [
                {
                  loader: "@badeball/cypress-cucumber-preprocessor/webpack",
                  options: config,
                },
              ],
            },
          ],
        },
      },
    })
  );

Para que funcione el webpack se debe instalar la dependencia npm install webpack --legacy-peer-deps usar el --legacy-peer-deps porque hay problemas con la versión de [email protected]

npm i @badeball/cypress-cucumber-preprocessor @cypress/webpack-preprocessor --legacy-peer-deps

https://marketplace.visualstudio.com/items?itemName=alexkrechik.cucumberautocomplete

Con esta extension vscode tendra el soporte que necesita para usar cucumber (gherkin)

Tampoco hace falta usar expresiones regulares en Cucumber si o si, porque se puede tranquilamente de la siguiente forma (noten que dentro de los {} hay que especificar el tipo de dato que estamos recibiendo):

login.feature

Feature: Login test

    Scenario: I login with correct credentials
        Given I am on the login page
        When I fill on my login and password with "username" and "password"
        Then I should validate that Im logged in

login.js

const {
  Given,
  When,
  Then,
} = require('@badeball/cypress-cucumber-preprocessor');
const { default: LoginWebPage } = require('../../../pages/LoginPage');

let loginPage;

Given('I am on the login page', () => {
  loginPage = new LoginWebPage();
  loginPage.visit();
  loginPage.isLoadPage();
});

When(
  'I fill on my login and password with {string} and {string}',
  (username, password) => {
    loginPage = new LoginWebPage();
    loginPage.doLogin(username, password);
  }
);

Then('I should validate that Im logged in', () => {
  loginPage = new LoginWebPage();
  loginPage.validateSuccessfulLogin();
});

**cypress.config.js** ```js const { defineConfig } = require("cypress"); const { addMatchImageSnapshotPlugin, } = require("cypress-image-snapshot/plugin"); const webpack = require("@cypress/webpack-preprocessor"); const preprocessor = require("@badeball/cypress-cucumber-preprocessor"); const values = {}; async function setupNodeEvents(on, config){ addMatchImageSnapshotPlugin(on, config); config.env.variable=process.env.NODE_ENV ?? 'NO HAY VARIABLE'; // INGRESA ALAS VAIABLES DE ENTORNO on("task", { guardar(valor){ const key = Object.keys(valor)[0]; values[key] = valor[key]; return null; }, obtener(key){ console.log('values', values); return values[key] ?? "No hay valor"; }, }); await preprocessor.addCucumberPreprocessorPlugin(on, config); on( "file:preprocessor", webpack({ webpackOptions: { resolve: { extensions: [".ts", ".js"], }, module: { rules: [ { test: /\.feature$/, use: [ { loader: "@badeball/cypress-cucumber-preprocessor/webpack", options: config, }, ], }, ], }, }, }) ); return config; }; module.exports = defineConfig({ e2e: { baseUrl: "https://pokedexpokemon.netlify.app", experimentalSessionAndOrigin: true, specPattern: "**/*.feature", supportFile: false, setupNodeEvents, excludeSpecPattern:[ "**/1-getting-started/*.js", "**/2-advanced-examples/*.js" ], //retries:2, /*retries: { runMode:2, openMode: 0 },*/ env:{ credentials: { user: "username", password: "password", }, }, specPattern:"**/*.feature", }, }); ```**login.js** ```js const { Given, When, Then, } = require('@badeball/cypress-cucumber-preprocessor'); const {loginPage} = require("../../pageObjects/loginPage.js"); Given('I am on the login page', () => { loginPage.visit(); loginPage.validatePageLogin(); }); When(`I fill in my login and password with {string} and {string}`, (username, password) => { loginPage.login(username, password); }); Then('I should validate that I\'m logged in', () => { loginPage.validateSuccessLogin(); }); ```**login.feature** ```js Feature: Login test Scenario: I login with correct credentials Given I am on the login page When I fill in my login and password with "username" and "password" Then I should validate that I'm logged in ```

Pasara entendimiento del negocio y de cada uno de los miembros es mejor que se vea una visión general de las pruebas automatizadas y que se entienda el comportamiento del usuario ya que es mas entendible para todos.

No se visualiza el link

En mi caso me funcionó con la siguiente configuración:

await preprocessor.addCucumberPreprocessorPlugin(on,config)

const options = {
webpackOptions: {
module: {
rules: [
{
test: /.feature$/,
use: [
{
loader: ‘@badeball/cypress-cucumber-preprocessor/webpack’,
options: config,
},
],
},
],
},
},

};

on(‘file:preprocessor’, webpack(options));

Los links de las dependencias requeridas en la clase

badeball/cypress-cucumber-preprocessor
cypress/webpack-preprocessor