'Cypress add delay to API call
I'm trying to test for a bug caused by a race condition based on which of two API calls returns first. To do this, I'd like to create a Cypress test that adds some delay to one of the routes by a second or two. I don't see anything documented on how to do that. Is there any easy way to do that? I tried stubbing window.fetch
but it didn't really work.
Solution 1:[1]
As of Cypress 6.0 you should use cy.intercept()
instead of cy.route()
. You can work with the request or response before its sent to the browser:
cy.intercept({
method: 'POST',
path: '*/pathtointercept/**',
}, (req) => {
//send the request with a delay value
req.reply({ delay: 30000 });
});
Solution 2:[2]
use cy.route()
options as described in the Cypress Docs:
cy.server()
cy.route({
method: 'GET',
url: '**/user/adam',
status: 200,
response: {
user: {name: 'adam'}
},
delay: 2000
})
cy.route({
method: 'GET',
url: '**/user/jane',
status: 200,
response: {
user: {name: 'jane'}
},
delay: 0
})
In order to make this case use "real" data, you may want to simply record the response of the route you want to delay by saving it to a fixture file, and then using that data to stub the route. There is an example of writing a response to JSON here
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 |