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 the above test file it will be ended up in the following error.
Screenshot 2021-06-17 at 4.36.26 PM.png
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 !!!!
