Leveraging the power of static in page object models with Cypress

After researching different examples of implementing end-to-end tests on Cypress, I noticed that many developers prefer to create a new object instead of using the static method. This raises questions about why they choose this approach over utilizing static for page-object methods. Since there is no need to modify data within the class itself and therefore no need to reference this, it seems unnecessary to have multiple instances of the same page. While Selenium employs page factory which necessitates creating a new object, it's unclear if there is a similar requirement in Cypress.

An example of creating a new object:

import { BasePage } from './BasePageClass'
import { navMenu } from './NavigationMenuClass';
import { queryPage } from './QueryPageClass';

export class MainPage extends BasePage  {
  constructor() {
    super();
    this.mainElement = 'body > .banner';
  }

  verifyElements() {
    super.verifyElements();
    cy.get(this.mainElement).find('.container h1').should('be.visible');
  }

  switchToQueryingPage() {
    navMenu.switchToQueryingPage();
    queryPage.verifyElements();
  }
};

export const mainPage = new MainPage();

An example using static:

import { BasePage } from './BasePageClass'
import { navMenu } from './NavigationMenuClass';
import { queryPage } from './QueryPageClass';

export default class MainPage extends BasePage  {
  static mainElement = 'body > .banner';

  constructor() {
    super();
  }

  static verifyElements() {
    super.verifyElements();
    cy.get(MainPage.mainElement).find('.container h1').should('be.visible');
  }

  static switchToQueryingPage() {
    navMenu.switchToQueryingPage();
    queryPage.verifyElements();
  }
};

Answer №1

My mentors have shared with me a set of commands for handling the buying process in our system. The main function is buyProduct, which involves multiple steps. I've broken down these steps into individual commands that can be utilized in various scenarios:

it('buyProductAsCustomer', ()=>{
    cy.login(customer)
    cy.shopFe_openProductByName(product.name)
    cy.shopFe_addProductToCart()
    cy.shopFe_openCheckoutFromCart()
    cy.shopFe_selectPaymentMethod("payWithCreditCardMethod")
    cy.shopFe_fillCheckoutFormAsCustomer(customer)
    cy.shopFe_checkoutPageGetOrderData()
    cy.shopFe_submitCheckoutForm()
    cy.shopFe_completePaymentWithCreditCard()
});
it('buyProductAsGuest', ()=>{
    cy.shopFe_openProductByName(product.name)
    cy.shopFe_addProductToCart()
    cy.shopFe_openCheckoutFromCart()
    cy.shopFe_selectPaymentMethod("payWithCashMethod")
    cy.shopFe_fillCheckoutFormAsGuest(guest)
    cy.shopFe_checkoutPageGetOrderData()
    cy.shopFe_submitCheckoutForm()
    cy.shopFe_completePaymentWithCreditCard()
});

Although these two cases could potentially be consolidated into a single command with multiple variables, the complexity grows over time. Therefore, we have opted to break them down into smaller, reusable parts that offer flexibility in their combinations.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring the capabilities of Vue JS to dynamically update data and model bindings within form

I need help creating a form that allows users to edit their comments. The challenge is to display the current value of the comment using dynamic data from v-for, while also binding the value to a model for sending it with a patch request. Here is an examp ...

Tips and tricks for selecting a specific element on a webpage using jQuery

How can I modify my AJAX form submission so that only the content within a span tag with the id "message" is alerted, instead of the entire response page? $.ajax({ url: '/accounts/login/', data: $(this).serialize(), success: function(ou ...

Ways to confine the tabindex within a specific div container

I am currently working on identifying examples of bad accessibility practices. Specifically, I am focusing on issues related to Keyboard Focus. The first example I have encountered is the lack of visibility when trying to navigate through a set of buttons. ...

Updating user interface dynamically based on the most recent data stream is crucial for a seamless user experience

I am facing a challenge where I need to update the indicator in the user interface based on real-time data. The requirement is that if there has been no data received in the last 30 seconds, the indicator should turn red. However, if data is received withi ...

Newbie in JavaScript baffled by typical testing protocol

Hello everyone, I've always been someone who just writes code, runs it, and fixes bugs as they come up. But now that I'm working on a medium-sized project with a team, I realize the importance of proper JavaScript testing. So here's my que ...

Eliminate entry upon checkbox completion from task schedule

Currently working on developing my own to-do list web application. I have set everything up except for one thing. I am trying to figure out how to remove a checkbox from the array when it is checked. Can someone please assist me in achieving this using DOM ...

Error in IONIC 3: The code is unable to read the 'nativeElement' property due to an undefined value, resulting in a TypeError

I am currently learning about IONIC 3 and working on an app that utilizes the Google Maps API. However, when I try to launch my app, I encounter the following error message: inicio.html Error: Uncaught (in promise): TypeError: Cannot read property ' ...

What is the process for importing Buffer into a Quasar app that is using Vite as the build tool

I'm having issues with integrating the eth-crypto module into my Quasar app that utilizes Vite. The errors I'm encountering are related to the absence of the Buffer object, which is expected since it's typically found in the front end. Is ...

Why does my React.js application still display outdated data from my Express server even after refreshing the webpage?

I have been working on a website using React.js and Express.js, following an online example to set up the basic code. I encountered an issue where the frontend did not update when I made a minor change to the array sent by Express.js. Express - users.js f ...

Get the data in string format and save it as a CSV file

I've coded a script that transforms a JSON object into comma-separated values using the ConvertToCSV function. Now I'm wondering how to save the variable csvData as a downloadable CSV file? The code is already wrapped inside a function triggered ...

Transforming an array into a string using Map Reduce

I am using an array map function to simplify an array of objects into a single string. const formatEmails: (arr: { "default" : string }[]) => string = (arr: { "default" : string }[]) => arr.map(e => e["default"]).reduce((e, i) => e + i + "; " ...

Tips for assigning a personalized value to an MUI Switch when it is in the off position

I am currently utilizing the MUI Switch component to create an On-Off button. I have manually set the value as "on" and it is functioning correctly when the switch is in the true state. However, there doesn't seem to be an option to change the default ...

An issue is encountered with the JavascriptExecutor while attempting to navigate to a different page using Selenium Webdriver

My goal is to capture user actions such as clicks, keypress, and other DOM events by adding JavaScript event listeners to the WebDriver instance. Everything works fine until I navigate to the next page, where I encounter an exception due to an undefined fu ...

Editing the dimensions of the input in Bootstrap 4

Is there a way to adjust the width of the input and select elements? I want the input element to take up more space while the select element occupies less space. <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel=" ...

Exploring JSON nested objects with jQuery UI Autocomplete

I'm attempting to implement the jQuery UI Autocomplete widget with a customized JSON feed received from an API. The format of the JSON data is as follows: { "SearchTerm": "ches", "HasDirectCountyHit": false, "DirectCountyHitId": null ...

D3js stacked bar graph displaying incorrect bar placements

Currently, I am attempting to create a stacked bar chart using D3js. My main issue lies in correctly setting the y and y0 attributes to ensure that the bars are displayed in their correct positions. It seems like there might be a miscalculation somewhere, ...

Unleashing the power of a headless browser with Selenium WebDriver using Chromedriver

I have a piece of code that I'm looking to adapt in order to use a hidden browser window for the same task. var webdriver = require('selenium-webdriver'); var chrome = require('selenium-webdriver/chrome'); var path = require(&apos ...

It appears that there may be an unhandled promise rejection for a request with ID 0, specifically a typeerror indicating that the body

import React from 'react'; import { FlatList, ActivityIndicator, Text, View } from 'react-native'; export default class DataFetcher extends React.Component { constructor(props){ super(props); this.state ={ isLoading: true} ...

Attempting to construct a webpage with the ability to create visual content

I've been struggling to kick off this project because I'm uncertain about what exactly I should be looking into. I would really appreciate any guidance on where or how to start. The concept is to enable users to upload an image of a postcard, in ...

React Native: Image not aligning vertically center in text within nested elements

Issue Description I am facing a challenge in nesting multiple images within a paragraph. If it were just a single line of text, I could have easily used a <View> with flexDirection: 'row'. Since that approach doesn't fit the requireme ...