QA Interview Hub · Knowledge base · Quizzes · Українська

Cypress › Command queue and asynchrony

How does .then() differ from .should() with a callback?

A callback in .should() is repeated until its assertions pass or the timeout ends, while a callback in .then() runs once. So a changing state is checked with .should(), and .then() is used to get a value and run further commands. A .should() callback must be safe to repeat, with no cy commands or side effects, and its return value is ignored.

Cypress · Asynchrony

The same expect passes in .should() but fails sometimes in .then(). What is the difference?

An order status updates about half a second after a click. In the test, .then(($el) => expect(...)) fails every other run, while .should(($el) => expect(...)) always passes. The difference is not syntax but how many times the callback runs.

How it works and why. The callback in .should() is repeated: Cypress runs the previous queries again (cy.get, .find and others) and the callback itself until all the assertions inside pass or the timeout ends, 4 seconds by default. The callback in .then() runs once, when the previous command has yielded a subject. So .then() is for getting a value and running the next commands, and .should(cb) is for many checks over one state that cannot be written as string assertions.

How many times the callback runs

should(cb): attempt 1 failedthe query and the callback are repeatedshould(cb): attempt 3 passedthe command is green, the subject is the samethen(cb): one attemptthe assert failed, the test fails at once
Figure 1. Should has room for the app to update, then does not: the first failed check stops the test.

This gives rules for a .should() callback. It may run many times, so it must be safe to repeat: no cy commands inside, no side effects, no accumulating state. A value it returns is ignored and the subject stays the one that arrived. In .then() it is the other way round: you can call cy commands inside, and the returned value becomes the new subject. Just do not mix the two: when the callback has cy commands, return the value through cy.wrap().

Example: the status after payment. Two forms with the same check:

// retried until the condition is true
cy.get('.status').should(($el) => {
  expect($el.text().trim()).to.eq('Paid');
});

// runs once: if the status has not updated yet, it fails
cy.get('.status').then(($el) => {
  expect($el.text().trim()).to.eq('Paid');
});

The second form passes only if the text has already changed by the time .then() runs. On a fast machine it will, on a slow CI it will not, so the test becomes flaky. And here is what must not go into .should():

cy.get('.row').should(($rows) => {
  cy.log('rows: ' + $rows.length); // error: a cy command inside should
  counter += 1;                    // side effect repeats on every retry
  expect($rows).to.have.length(3);
});

Here Cypress fails right away: invoking cy commands inside a .should() callback is forbidden. And the counter would grow as many times as there were retries, so its value is unpredictable. The right layout: first wait for the state through .should(), and only then take the value through .then().

cy.get('.row').should('have.length', 3);   // wait for the state
cy.get('.row').then(($rows) => {          // then take a value
  cy.log('rows: ' + $rows.length);
  return cy.wrap($rows.length);                    // the next subject: a number
});

Limits and alternatives. Simple checks need no callback at all: .should('have.text', 'Paid') or .should('have.length', 3) retry the same way and read better. A callback is needed when the check combines several conditions or needs a calculation, for example from a sum of prices. If you need to repeat not an assertion but your own logic (polling an API, other cy commands), there is no built-in retry for .then(): use cy.request in a recursive function or cy.waitUntil from a plugin.

And in Playwright:

The analogue of .should(cb) with retries is expect.poll() for a value or expect(async () => { ... }).toPass() for a block of assertions. A one-time check expect(await locator.textContent()).toBe(...) corresponds to .then in Cypress.

Typical mistakes.

  • Checking a changing state in .then(): the test depends on the speed of the app.
  • Calling cy commands or doing side effects inside a .should() callback.
  • Expecting the value returned from .should(cb) to go on: it is ignored.
  • Writing a long .should() callback when a string assertion would do.

Check yourself

A .should(cb) callback has counter++. Why is its value unpredictable at the end?

Answer

Because the should callback is repeated until the assertions pass, so counter grows on every attempt. A should callback must be safe to repeat: no side effects and no cy commands inside.

When do you take .then() rather than .should(cb)?

Answer

When you need to get a value once and run the next commands, for example cy commands that use it. For checking a state that changes over time, take .should.

In the interview. Junior: Should with a callback is repeated: Cypress looks the element up again and runs the check until the assertion passes. Then runs exactly once, it is for getting a value and continuing the chain. You must not call other cy commands inside should. Middle/Senior: A practical rule: a state that changes over time I check through should, and values I take through then. A should callback must be safe to repeat: no side effects and no counters. The value returned from it is ignored, while from then it becomes the new subject.

More articles in this chapter