0

I have a textbox. When user types something I will hit api and insert a list of items <ul> into DOM. On textbox blur, I will remove <ul> from DOM.

    it('Category search', () => {
        cy.intercept('GET', `http://localhost:3000/categories/query**`, {fixture: 'categories.json'})
        cy.visit(`http://localhost:3000/items`)
        cy.clock()
        cy.tick(2000)
        cy.get('#category').click().type('o')
        cy.get('ul[class*="category-list"]').its('length').should('eq', 10)
      });

Cypress test can't find cy.get('ul[class*="category-list"]'). Because, when cypress reaches to this line my textbox loses its focus. So, ul tag removed automatically.

Can anyone please help? Thanks in advance.

Siva
  • 113
  • 1
  • 2
  • 9
  • Try chaining it in a `.should()` like: `cy.get('#category').click().type('o').should(()=>{cy.get('ul[class*="category-list"]').its('length').should('eq', 10)})`. Also pls adjust the title of the question pls it is misleading. I suggest: How to keep an input focused durin a cypress test@ – Rosen Mihaylov May 28 '21 at 10:12
  • @RosenMihaylov Still textbox loses its focus :( . Thanks for your edit suggestion – Siva May 28 '21 at 10:22
  • @Siva Can you post the error that you are getting ? – Alapan Das May 28 '21 at 10:28
  • I found a JS sulution suggested here: https://stackoverflow.com/questions/15670277/maintain-focus-on-an-input-tag – Rosen Mihaylov May 28 '21 at 11:21

1 Answers1

0

It's possible that the input is not losing focus. Add .focused() to the test to check

cy.get('#category').type('o');     // Note, docs say type() has click() built in
cy.focused().then(console.log);    // check the dev console to see which element has focus

The way you're testing <ul> doesn't look correct, usually there is one <ul> and several <li> within, so try

cy.get('#category').type('o');     
cy.focused().then($el => {

  expect($el[0].id).to.eq('category');     // confirm focus still on input

  cy.get('ul[class*="category-list"]')     // just to be sure, repeats if testing too early
    .should('be.visible');                 // (maybe delayed by api call)

  cy.get('ul[class*="category-list"] li')  // get the <li> not the <ul>
    .should('have.length', 10);            // repeats if list not yet filled
                                           // Note need to avoid "its('length')"
                                           // for retry of <li> query to work

);