skip to Main Content

Operating System: Windows 11

Software Version: Cypress 13.9.0

Hi, im using this custom function, to use a custom dropdown input a website in my company has.
Said website is incredibly flaky, and it queries the options for the dropdown only when you click on input.

That makes it super weird to work on, because on any moment, the input can be without options, only to have options a second later. Also, the input may autocomplete itself based on what you selected on another input

I attached an screenshot of the website, if that helps.

For that kind of dropdown, i developed this function, and it worked pretty much alright for a couple months.

Cypress.Commands.add(
  "selectOptionFromDropdown",
  (dropdownSelector, optionValue, config = {}) => {
    const { exactMatch = false, waitTime = 100 } = config;

    // Convert to lowercase if its not a number
    if (isNaN(optionValue)) {
      optionValue = optionValue.toLowerCase();
    }

    // Check if the dropdown already contains the option
    cy.get(dropdownSelector).then((dropdownElement) => {
      if (dropdownElement.prop("readonly")) {
        cy.log("ELEMENT IS READONLY, SHOULD BE RETURNING");
      } else {
        // Check if the dropdown is not read-only
        cy.get(dropdownSelector).should("not.have.attr", "readonly");

        // Get the dropdown element and clear its content
        cy.get(dropdownSelector).clear();

        // Type the text passed as a parameter
        cy.get(dropdownSelector).type(optionValue);

        // Select the mat-option based on specificity
        cy.get(`mat-option`)
          .filter((index, el) => {
            const text = el.textContent.trim().toLowerCase();
            if (exactMatch) {
              return new RegExp(`^${optionValue}$`, "i").test(text);
            }
            return text.includes(optionValue);
          })
          .click();

        // Wait for the specified time
        cy.wait(waitTime);
      }
    });
  }
);

And i use it like this

        cy.selectOptionFromDropdown(
          `[data-cy="input-productor"]`,
          "UNIDAD DE NEGOCIOS DE VENTA DIRECTA"
        );
        cy.selectOptionFromDropdown(
          `[data-cy="input-provincia"]`,
          persona.provincia
        );
        cy.selectOptionFromDropdown(
          `[data-cy="input-tipoPersona"]`,
          persona.tipoPersona
        );
        cy.selectOptionFromDropdown(
          `[data-cy="input-medioPago"]`,
          persona.medioPago
        );
        cy.selectOptionFromDropdown(
          `[data-cy="input-origenPago"]`,
          persona.origenPago
        );
        cy.selectOptionFromDropdown(
          `[data-cy="input-condicionIva"]`,
          persona.condicionIVA
        );

But suddenly, this error started appearing

The following error originated from your test code, not from Cypress.

> Cypress detected that you returned a promise from a command while also invoking one or more cy commands in that promise.

The command that returned the promise was:

> cy.click()

The cy command you invoked inside the promise was:

> cy.task()

Because Cypress commands are already promise-like, you don't need to wrap them or return your own promise.

Cypress will resolve your command with whatever the final Cypress command yields.

The reason this is an error instead of a warning is because Cypress internally queues commands serially whereas Promises execute as soon as they are invoked. Attempting to reconcile this would prevent Cypress from ever resolving.

When Cypress detects uncaught errors originating from your test code it will automatically fail the current test.Learn more
cypress/support/commands.js:91:12
  89 |             return text.includes(optionValue);
  90 |           })
> 91 |           .click();
     |            ^
  92 | 
  93 |         // Wait for the specified time
  94 |         cy.wait(waitTime);

The line where the error occurs is not always the same.

Sometimes, it just happens outside of the function

The function was working months ago, and i dont know how to solve this issue.

Maybe i will have to get in touch with the development team, to make the inputs disabled while they are getting data from the backend?

2

Answers


  1. Chosen as BEST ANSWER

    The error was this piece of code somewhere else in the code:

    cy.on("uncaught:exception", (err, runnable) => {
      cy.task("log", err);
      return false;
    });
    

    and this in my cypress.config

    module.exports = defineConfig({
        e2e: {
            on("task", {
                log(message) {
                    console.log(message);
                    return null;
                },
            });
         }
    });
    

    That was the culprit, the uncaught exceptions happened randomly on some inputs, that's why it was failing at random


  2. The technical reason why this is a problem is that cy.on("uncaught:exception"... is an event handler which responds to events as they occur, not in the orderly and predictable fashion that Cypress expects from the command queue.

    It’s like you injected the cy.task() randomly into the command queue while the queue is running.

    But Cypress stores a lot of state internally based on the command sequence defined in the test, and "injecting" another command can disrupt the internal queue state in an unpredictable way, causing flaky test results.

    The best rule of thumb is not to use any cy. commands inside an event handler.

    For something like the task logging messages to the terminal, you might use a buffer to hold messages and log them in an afterEach() hook.

    If you want to set up the uncaught:exception event handler outside of the test, use Cypress.on().

    const messageBuffer = []
    
    Cypress.on("uncaught:exception", (err, runnable) => {
      messageBuffer.push(err)
      return false;
    })
    
    afterEach(() => {
      messageBuffer.forEach(msg => {
      cy.task("log", msg);
    })
    
    it('runs my test', () => {
    
    })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search