How to use one or more cy commands with in a custom command in Cypress

Lakmal Liyanage
Quality Engineering Blog

--

When returning any value or an object from a function within custom commands and at the same time if try to use another cy command or commands within that command there might be a case where ended up with the following error.

What’s the problem here?

Let’s check an example:

command.js

Cypress.Commands.add('generateUser', () => {
....
......
const user = {
...
...
};
cy.log(user);return user;
});

test file

describe('test description', () => {
it('example 1', () => {
cy.generateUser().then(data => {
cy.log(data);
})
})
})

When run above test file it will be ended up in the following error.

Next, how to fix this?

Next, how to fix this?

The simplest fix is to chain the command used as follows.

command.js

Cypress.Commands.add('generateUser', () => {
....
......
const user = {
...
...
};
cy.log(user);return cy.wrap(user);
});

What’s happen when chain the command.

When wrapping the promises returned by the application code, cypress commands automatically wait for a promise to be resolved (in above scenario cy.log()) before continuing with the yielded value for the next command or assertion.

Find more details about cy.wrap()

Happy Testing !!!!

--

--