Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use values from DOM in cypress test?

Tags:

cypress

if I have a page containing:

  <span data-testid="credit-balance">
    10
  </span>

In Cypress, how do I extract the value to a variable to use in tests?

Something along the lines of:

const creditBalance = cy.get('[data-testid="credit-balance"]').value();
like image 807
JD. Avatar asked Jun 06 '18 23:06

JD.


People also ask

How do you get DOM elements in Cypress?

You can use cy. get() for aliases of primitives, regular objects, or even DOM elements. When using aliases with DOM elements, Cypress will query the DOM again if the previously aliased DOM element has gone stale. You can read more about aliasing objects and elements in our Core Concept Guide.

How do you get attribute values in Cypress?

Cypress provides a way to get the element by attribute name. Since it supports all the different types of CSS selectors, you can pass the CSS selectors inside the cy. get() command to get an element. However, id and class are also attributes.


2 Answers

Assigning return values with const, var, and let is considered an anti pattern while using Cypress. However, when you find yourself wanting to do so, is best practice to accomplish this with closures.

it("uses closures to reference dom element", () => {

   cy.get("[data-testid=credit-balance]").then(($span) => {

   // $span is the object that the previous command yielded

   const creditBalance = $span.text();

   cy.log(creditBalance);

  })

});

Another way to do this would be to use Aliases if you want to store and compare values or share values between tests using hooks.

it("aliasing the value from dom element", () => {

  cy.get("[data-testid=credit-balance]").as("creditBalance")

  cy.get("@creditBalance").should("contain", 10)

});

How you approach this really depends on the objective of your test. I recommend checking out more examples from the documentation: try Variables and Aliases , Best Practices, and FAQ

like image 97
Valerie Thoma Avatar answered Sep 23 '22 11:09

Valerie Thoma


If you would like to retrieve the value and perform any assertions with it, a fast, efficient method would also be the use .invoke

it('Getting the value and performing an assertion', () =>{
   cy.get('selector').invoke('val').should('eq',10) 
})

Doc

like image 28
Schan9 Avatar answered Sep 20 '22 11:09

Schan9