'Why is Cypress not finding my button using name or id selectors? You can use ID's to select any element

I am running simple tests in Cypress on facebook.com just to get familiar with automated testing. //Below replace **'ed code with your own credentials.

    /// <reference types="cypress" />
    
    context('tests login', function () {
        it('connects to facebook and logs in', function() {
            cy.visit('https://www.facebook.com/login');
            cy.get('input[name=email]').type('********');
            cy.get('input[name=pass]').type('*******');
            cy.get('button[id=loginbutton]').click();
        }) 
    })

So the error I get is an Assertion Error that says " Timed out retrying after 4000ms: Expected to find element: button[id=loginbutton], but never found it. "

You can check the login button element using chrome dev tools. I tried using both (separately) name and id (name=login, id=loginbutton).

Let me know if you can help. I wouldn't be surprised if it was something very simple, I just can't seem to figure it out.


Edit:

You can use ID's to select any element. So there is no reason to include the element in cy.get(...).



Solution 1:[1]

The facebook login page is different under Cypress than a browser. Cypress is suppressing something during the page load, and it's going to a fallback page.

In the browser, the form is full-page with this HTML

<button value="1" ...
  id="loginbutton" name="login" tabindex="0" type="submit">Log In</button>

but in the Cypress test it is in the toolbar and the HTML is

<td>
  <label ... id="loginbutton" >
    <input />
  </label>
</td>

so your test can work either way if you drop the element tag from the selector

cy.visit('https://www.facebook.com/login');
cy.get('input[name=email]').type('********');
cy.get('input[name=pass]').type('*******');
cy.get('[id=loginbutton]').click();

or

cy.visit('https://www.facebook.com/login');
cy.get('input[name=email]').type('********');
cy.get('input[name=pass]').type('*******');
cy.get('#loginbutton').click();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1