Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an reusable element similar to Selenium extend elements in Cypress.io?

In Selenium, it's possible to extend elements. This makes it possible to have a set of reusable custom elements for testing.

For example, we can have a getText method added.

public static string GetText(this IWebDriver driver)
{
    return driver.FindElement(By.TagName("body")).Text;
}

And re-use it as follows:

myElement.getText();

This example is detailed here: http://www.vcskicks.com/selenium-extensions.php

Is there a way to replicate this behavior in Cypress.io? Or do we need to query and call the same methods to get the data?

like image 293
nipuna777 Avatar asked Dec 13 '22 19:12

nipuna777


1 Answers

You can accomplish this using simple functions. For example, you could move several functions into a utils.js.

export const getByText = (text) => cy.contains(text)

And then import those methods into your spec file.

import { getByText } from './utils'

it('finds the element', () => {
  getByText('Jane Lane')
})

You could alternatively create a custom command, but that's sometimes not necessary as noted in the best practices.

like image 196
Jennifer Shehane Avatar answered Dec 31 '22 14:12

Jennifer Shehane