How do you combine Cypress with Promises and ordinary async code?
cy.wrap waits for a Promise, but the Promise is created when the function is called, so cy.wrap(fn()) starts fn at once. To make the call happen at the right moment, put it inside .then(). Code that must run in Node, such as a database or files, goes into cy.task. A test that calls cy commands must not return a Promise.
Cypress · Asynchrony
An async helper resets the database, but at the wrong moment. How do you combine Promises and the command queue in Cypress?
A project has a ready resetDb() function built on Promises that resets test data. It is called in a test through cy.wrap(resetDb()), and people are surprised: the reset happens before the cy.visit() that stands earlier. This lesson explains when ordinary code runs, how cy.wrap works with a Promise and where cy.task is needed.
How it works and why. cy.wrap(promise) adds a command to the queue that waits for the Promise. When the Promise settles, Cypress yields its value to the next command, and if it rejects, the test fails. The waiting time is limited by the timeout option, which defaults to defaultCommandTimeout. But the Promise itself is created when the function is called, that is at the moment the test body is still building the queue. So cy.wrap(resetDb()) starts resetDb() immediately, not after the earlier commands. The documentation directly recommends a chain through .then() for this case.
Where and when code runs
For code that should not run in the browser at all (a database, the file system, token generation through a library), use cy.task(). The handler lives in the Node process, is defined in setupNodeEvents and returns a value or a Promise. The result comes back into the test as a subject.
Example: resetting the database. First the mistake:
cy.visit('/admin'); // queued
cy.wrap(resetDb()); // resetDb() starts now, before visit
cy.get('[data-cy=users]').should('have.length', 0);
Here the check expects an empty list, while the reset may have happened even before the page opened. The fix, where the Promise is created already inside the queue:
cy.visit('/admin');
cy.wrap(null).then(() => resetDb()); // a Promise at the right point of the queue
cy.get('[data-cy=users]').should('have.length', 0);
// or where the code must run in Node
cy.task('db:reset');
A handler for cy.task that lives outside the browser:
// cypress.config.ts
setupNodeEvents(on) {
on('task', {
'db:getUser': async ({ email }) => {
return (await db.users.findOne({ email })) ?? null;
},
});
},
The result of cy.task('db:getUser', ...) can be checked right away: .its('status').should('eq', 'active'). The handler must return a value, and undefined is not allowed: return null.
Limits and alternatives. The main rule: do not mix Promise style and the queue in one block. Cypress does not allow returning a Promise from a test or a callback if cy commands are invoked inside, and it shows an error about mixing:
it('mixed', () => {
return fetch('/api/ping').then(() => {
cy.get('h1').should('be.visible'); // a cy command inside a returned Promise
});
});
Inside .then(async () => { ... }) you can await Promises, but not cy commands. If the logic is complex, move it into cy.task (Node) or a custom command made of cy chains. For requests to the app itself, cy.request is often better than fetch: it uses browser cookies and works in the queue.
There is no mixing problem: it is plain async/await, so Promise.all and any libraries work. An analogue of cy.task is not needed, because the test already runs in Node: you can reach the database straight from the test.
For seniors. cy.wrap, cy.request and cy.task solve different problems. cy.wrap only waits for a Promise created in the browser. cy.request runs on the Cypress side, outside CORS limits, and suits calls to the application's API. cy.task runs code in Node, but its arguments and result must be serialisable (no functions or classes), and it has its own timeout, taskTimeout, 60 seconds by default, while defaultCommandTimeout is only 4. In a framework, async helpers that need Node live in setupNodeEvents and are called through a thin custom command, so tests do not know where the work runs.
Typical mistakes.
- Writing
cy.wrap(doSomething())and assumingdoSomethingstarts after the earlier commands. - Returning a Promise from a test where
cycommands are invoked. - Calling
cycommands inside anasync.then()callback afterawait. - Querying the database from browser code instead of
cy.task.
Check yourself
How does cy.wrap(getToken()) differ from cy.wrap(null).then(() => getToken())?
Answer
In the first case getToken() is called immediately while the queue is being built, before the earlier cy commands. In the second the call happens in the queue, after the earlier commands, and Cypress waits for the Promise returned from then.
When do you need cy.task rather than cy.wrap?
Answer
When the code must run in Node, not in the browser: a database, files, libraries that do not work in a browser. cy.wrap only waits for a Promise created in the browser code of the test.