Warm tip: This article is reproduced from stackoverflow.com, please click
cypress javascript

How do you call `request` within a Cypress custom command?

发布于 2020-04-07 23:22:11

How do you call request within a Cypress custom command?

Cypress.Commands.add('factory', async (name, attributes) => {
  const response = await cy.request('POST', '/cypress/factories', {
    name,
    attributes: attributes || {}
  });
  return response;
});

results in ..

The command that returned the promise was: > cy.factory() .
The cy command you invoked inside the promise was: > cy.request() .
Because Cypress commands are already promise-like, you don't need to wrap them .
or return your own promise.Cypress will resolve your command with .
whatever the final Cypress command yields.

Questioner
GN.
Viewed
83
balzafin 2020-02-01 05:18

Like the message says, Cypress will resolve the response for you, so no need to return anything.

Cypress.Commands.add('factory',(name, attributes) => {
  cy.request('POST', '/cypress/factories', {
    name,
    attributes: attributes || {}
  });
});

You can use the command with then

cy.factory(name, attributes).then(response => {
  console.log(response)
})