DEV Community

John Peters
John Peters

Posted on • Updated on

Cypress Observables in 20 Minutes

Consider this exportable function



//get all divs and return an Observable
export function getDivs() :Observable<any> {
  return   
    // an observable using the from operator in RxJS
    from(
      //get all divs; then return them to the observable
      cy.get("div").then((divs) => {
        //this happens sometime in the future
        return divs;
      })
    );
}


Enter fullscreen mode Exit fullscreen mode

Importing Functions in Cypress Tests



import {getDivs} from "../../support/commands"

context('Actions', () => {
  beforeEach(() => {
    cy.visit('https://example.cypress.io/commands/actions')
  })
  it("it proves how we can use observables for any cypress result", () => {
   //lets use our new Cypress Function
    getDivs().subscribe(divs => {
      debugger;
    });
  });


Enter fullscreen mode Exit fullscreen mode

When we hit the debugger statement in the test, pressed F12 and looked into what was returned, we saw that there were 105 Divs on this page

Alt Text

Note that Cypress does not return an array of elements rather, it returns an array of { index : element }. This is why the divs.map function will map numbers as the key, and not elements. Let's create a helper function to strip out the numbers.



//convert to just an array of elements
export function ToArray(eles) {
  let elementArray = [];
  eles.each((item) => {
    elementArray.push(eles[item]);
  });
  return elementArray;
}

//How to use ToArray 
let divArray = ToArray(divs);
//map now works as expected
let collection = divArray.map(function (div) {
    //these are html elements, we may access their properties
    return div.textContent;
});



Enter fullscreen mode Exit fullscreen mode

We discovered the exportable function, contained in the command.js file worked as a container for our functions.

This bypasses the Cypress Commands Syntax which doesn't work; for Typescript intellisense.

The amazing thing was that the time it took to get all divs was as fast as:

document.getElementsByTagName('div')

It's very impressive that Cypress fully supports the module system and the ability to export/import. When we import our own functions, we have intellisense for any of our custom commands.

Maybe we should name this construct the 'Cypress Custom Function'. I predict a huge market for Cypress Extensions could emerge using this construct.

JWP2020

Top comments (0)