How to wait for cy.request() to complete its then() block? #9377
-
If I have the following code: let item
const createItem = () => {
item = { name: 'thing', colour: 'red' }
cy.request('POST', '/api/create', item)
.then((response) => {
item.id = response.body.id
console.log(`ID from API: ${item.id}`)
})
}
describe('Item', () => {
it('creates an item', () => {
createItem()
console.log(`ID is now: ${item.id}`)
cy.visit(`/item/${item.id}`)
// tests here
}
} then I see this in the console:
rather than
and the test tries to navigate to Obviously, this is because I tried aliasing: The only way I've found to beat this so far is to call |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 2 replies
-
Please read our documentation that explains how every test command is queued and is asynchronous https://docs.cypress.io/guides/core-concepts/introduction-to-cypress.html#Commands-Are-Asynchronous In your example: createItem()
console.log(`ID is now: ${item.id}`)
cy.visit(`/item/${item.id}`) the createItem()
cy.then(() => {
console.log(`ID is now: ${item.id}`)
})
cy.visit(`/item/${item.id}`) or return Cypress object from const createItem = () => {
item = { name: 'thing', colour: 'red' }
return cy.request('POST', '/api/create', item)
.then((response) => {
item.id = response.body.id
console.log(`ID from API: ${item.id}`)
})
}
createItem()
.then(() => {
console.log(`ID is now: ${item.id}`)
})
cy.visit(`/item/${item.id}`) |
Beta Was this translation helpful? Give feedback.
-
Thanks — I thought I had tried that, but obviously not! I suspect I was trying to |
Beta Was this translation helpful? Give feedback.
-
I've got a very similar question which I've posted here, and I'm not able to fix it. Would you mind taking a look at it and give me any suggestion? Thank you! |
Beta Was this translation helpful? Give feedback.
Please read our documentation that explains how every test command is queued and is asynchronous https://docs.cypress.io/guides/core-concepts/introduction-to-cypress.html#Commands-Are-Asynchronous
In your example:
the
console.log
immediately executes, whilecreateItem
andcy.visit
are enqueued to be executed. If you want theconsole.log
execute to run AFTER the Cypress commands insidecreateItem
finish, then you can do one of these thingsor return Cypress object from
createItem
which allows you to chain more t…