Search code examples
testingautomated-testscypresse2e-testing

How to scroll to the very top of the page in Cypress


I am trying to fetch an api and mock data with my own data on search. Below is my cypress code.

In my UI, there is a searchbox at the near top of the page below app header bar. The problem is after fetching data and render, cypress auto scroll the page to the bottom a little bit and what happens is that searchbar is covered by app header bar. So, to type into search box is not possible anymore.

it.only("should fetch data on Search and display data", () => {
    const searchText = "product1";
    const apiURL = `products?statuses=[]`;
    
    cy.intercept("GET", apiURL, {
      statusCode : 200,
      body : myMockedResponse
    }).as("getProducts");
    // cy.scrollTo("top", { duration: 500, ensureScrollable : false }); // not working
    cy.viewport(1000, 10000); // this is working
    cy.visit(Product_Path); 
    cy.viewport(1280, 1200);

    cy.wait("@getProducts").then(xhr => {
      cy.wait(2000);

      if (xhr.response) {
        const responseData = xhr.response.body.data;
        const searchedData = responseData.filter(d => d.name.toLowerCase().includes(searchText.toLowerCase())); 

        expect(xhr.response.statusCode).to.equal(200);

        // cy.get("[data-test=search-input]").scrollIntoView(); not working
        // cy.scrollTo("top"); not working
        // cy.scrollTo(0, 0); not working
        cy.get("[data-test=search-input]").type(searchText);

       // assertions using searchedData
      }
    });
  });

So, I tried setting really long viewport-height to the page to fit all the content (when it is not fit in viewport) like really crazy value - 10000. and it is working. But, I don't want to use that.

So, I found scrollTo and tried it. Not working. What do I need?

The html structure is:

<div data-test="search-input" class="search-input"><input name="search" placeholder="Search" type="text" class="search-input mr-5 rounded-3 form-control"></div>

Solution

  • I found a solution, to disable auto-scroll this cypress behavior: Adding "scrollBehavior": false inside cypress.config.js file.