Cypess How to test a button attribute change during rest call via intercepting

Viewed 51

I have a (form submit) button that having an attribute disabled when being clicked. It became available again when the call is finished.

Because it happens very fast. I want to find a way to capture this behaviour during the api call

What I tried:

cy.intercept('POST', '/api/item/1', (req) => {
  req.continue((res) => {
    cy.findByRole('button', { name: /button0/i })
      .should('exist')
      .should('have.attr', 'disabled');
    res.send(200, { name: 'aa' })
  });
});

cy.findByRole('button', { name: /button0/i }).click();

However it gives me error Cypress detected that you returned a promise from a command while also invoking one or more cy commands in that promise.

I found a workaround that If i do

cy.intercept('POST', '/api/item/1', (req) => {
  req.continue((res) => {
    res.setDelay(1000);
    res.send(200, { name: 'aa' })
  });
});

cy.findByRole('button', { name: /button0/i }).click();
cy.findByRole('button', { name: /button0/i })
      .should('exist')
      .should('have.attr', 'disabled');

Then it has enough time to capture the attribute change during the delay.

However I don't think it's robust using arbitrary delay in a test. Is there better way to test this behaviour using cyprss?

1 Answers

You really don't need 1000 ms delay in the intercept.

Start with 10ms and work up. If you want to finely tune the wait, do a burn test Burning Tests with cypress-grep to make sure your delay is high enough.

On the test command side, cut down the steps

cy.findByRole('button', { name: /button0/i })
  .click()
//cy.findByRole('button', { name: /button0/i })  // don't do this again
//      .should('exist')                         // already checked in findByRole
  .should('have.attr', 'disabled')               // this is all you need
                                                 // will retry until attr appears

Final note, .setDelay() is simple and straight-forward, don't get hung up on using it when it makes your code easier.

Related