https://cypress.io logo
Custom query calling an async node function via cy...
# i-need-help
m
We have some custom commands that can be flaky thanks to race conditions. The commands are used to retrieve items from a Firebase emulator backend. I'd like to rewrite these commands as custom queries in order to benefit from the native retry-ability of the latter. The commands currently use cy.task() to run custom retrieval tasks in Node. Here's an example a custom command:
Copy code
javascript
Cypress.Commands.add("getFirebaseUserByEmail", (email) => {  
    return cy.task("getFirebaseUserByEmail", { email })
})
getFirebaseUserByEmail:
Copy code
javascript
export async function getFirebaseUserByEmail({ email }: { email: string }): Promise<UserRecord | null> {  
  try {    
    const user = await getAuth().getUserByEmail(email.toLocaleLowerCase())    
    return user
  } catch (error) {    
    if (error.code === 'auth/user-not-found') {      
      return null    
  }    
throw error 
}}
That works as a custom command. But, if the user hasn't been created in the backend yet, the command will immediately fail thus failing the e2e test. I'd like to change this to a custom query so that Cypress will retry the user retrieval until the timeout threshold is reached. Here's my attempt at that:
Copy code
javascript
Cypress.Commands.addQuery('getFirebaseUserByEmail', function getFirebaseUserByEmail(email) {
  return () => {      
    cy.task('getFirebaseUserByEmail', { email }).then(user => {
      return user      
    })    
  }  
})
That command fails with an error:
Timed out retrying after 4000ms: Cypress detected that you returned a promise from a command while also invoking one or more cy commands in that promise.
Is it just not possible to do anything asynchronously within a custom query?