Cypress test with Debounce input

Viewed 561

Please some help.

I have a debounced handleChange function to an input. The debounced function is:

const useDebounce = (func, timeout = 500) => {
  let timer;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => { func.apply(this, args); }, timeout);
  };
}

export default useDebounce

And handler is:

const handleChange = (e) => {
    onData({ name: e.target.name, value: e.target.value });
};
const debouncedHandleChange = useDebounce((e) => handleChange(e), 700);

The debounce function is fetching data from an API. If i use the browser, it's work fine.

Note: I used in the same code the debounce function of lodash and it's ok, but I should use the useDebounce function.

The cypress test is:

describe('Testing autoload PreForm information [Desktop]', () => {
  beforeEach(() => {
  cy.loadingCucaCorpContact();
      cy.visit('/');
      cy.setViewportXL();
  });

  it('should display autoloaded information', () => {
      cy.findAllByText('Despacho y retiro').click();
      cy.findAllByText('No ha llegado mi producto').click();
      cy.get('[data-cy=inputrutNotReceived]').type('11111111-1');
      cy.get('[data-cy=inputorderIdNotReceived]').type('777777777');
      cy.contains(
          'Lo sentimos, estamos presentando algunas dificultades, vuelve a intentarlo dentro de un momento',
          { timeout: 5000 }
    );
  });
});

Well, the test is not succeded because isn't calling the API. I used examples like:

cy.wait(6000)
...
cy.clock()
cy.tick(500)
...
cy.get('[data-cy=inputorderIdNotReceived]').type('777777777').trigger('change);

... and still doesn't work

Any idea?

Best regards.

1 Answers

Debounce is always a bit mind-boggling, but I notice you have sent in 700ms in the app but in the test you tick for just 500ms.

First, try with cy.tick(710).

If that does not work, remove the cy.clock() and cy.tick() as these actually stop the debounce from firing (setTimout() is effectively frozen by these commands).

React hooks and cy.wait(0)

useDebounce looks like it's a custom hook, so the next thing to try is adding cy.wait(0) to release the JS thread and allow React hooks to process.

cy.findAllByText('Despacho y retiro').click();
cy.findAllByText('No ha llegado mi producto').click();

cy.get('[data-cy=inputrutNotReceived]').type('11111111-1');
cy.wait(0)

cy.get('[data-cy=inputorderIdNotReceived]').type('777777777');
cy.wait(0)

cy.contains('Lo sentimos', { timeout: 5000 })

.type() delay option

Third option, Cypress .type() has a delay option that may be useful, but it's between keypresses, but debounce is to delay sending the whole string to the API.

In any case, it's worth a try because complicated handler may not pick up keys entered by Cypress at the default rate of 10ms.

cy.get('[data-cy=inputrutNotReceived]').type('11111111-1', {delay: 100});
Related