Cypress click element by ID / XPATH / Name?

前端 未结 5 1889
一整个雨季
一整个雨季 2021-02-20 11:40

I want to click on an element by XPATH / ID and not the default cypress locator, is it possible?

In selenium I can use find element by XPATH for example:



        
相关标签:
5条回答
  • 2021-02-20 11:52

    #hdtb-msb-vis is an ID-selector and .category is a class-selector. But you should be able to select purely by the class-selector

    cy.get('.category')
      .click()
    

    But if that class is not unique you can click it via the ID and then the class:

    cy.get('#hdtb-msb-vis')
      .find('.category')
      .click()
    
    0 讨论(0)
  • 2021-02-20 11:53

    The first question contains two different selectors, the first (selenium) look for an id category and the second for a class category.

    In fact :

    d.findElement(By.id("category")).click();
    ==
    cy.get('#category').click()
    

    So yes you could select an element by it's ID !

    If (and i don't think) you want to have others possibility for selecting your elments look for jquery selector (jquery is exposed in cypress)

    0 讨论(0)
  • 2021-02-20 11:54

    There are 2 things to be done if trying to use xpath in cypress:-

    1. In the file 'index.js' which sits under the folder 'YourProject'->'cypress'->'support', add the entry "require('cypress-xpath')"
    2. In the file 'Dockerfile.cypress' which sits under the folder 'YourProject'->'configuration'->'docker', add the entry "RUN npm install cypress-xpath"

    That's all you need to use all the xpath functions to uniquely identify all elements in your cypress tests. I personally prefer using xpath since this gives me more control on the UI elements. Hope this will make life more easier in using cypress.

    0 讨论(0)
  • 2021-02-20 11:55

    I think, it is possible by adding a plug-in as suggested in Cypress website, please refer the following link https://docs.cypress.io/plugins/#content. If you refer the custom command section you could see cypress-xpath which takes you to following github link https://github.com/cypress-io/cypress-xpath

    npm install -D cypress-xpath
    

    Then include in your project's cypress/support/index.js

    require('cypress-xpath')
    

    Sample usage given below:

    it('finds list items', () => {
      cy.xpath('//ul[@class="todo-list"]//li')
        .should('have.length', 3)
    })
    

    Please try after installing the plug-in and updating the support/index.js file.

    0 讨论(0)
  • 2021-02-20 11:57

    In Cypress, it works like this:

    cy.get('button[id="category"]').click()
    

    Notice that I just used button as an example here, you should replace that with the label of your element: div, select, textarea, etc...

    0 讨论(0)
提交回复
热议问题