Conditional Waiting in Cypress

Ajdin Mustafic
2 min readFeb 21, 2023

By using a recursive function, you can repeatedly wait for the request until you get the desired response

Test Case

Our test case involves an existing user (permanent user) who invites a new user via email. The new user receives a registration link and registers for the Determ application. After the new user has been registered and has access to the app, we need to delete them to “clean up” after the test. However, we don’t want to delete the existing user, so we need to check the user ID before deleting the user.

Solution

To delete the newly created user, we need to intercept and wait for a specific API request that contains the user’s access token. However, the same request is also sent for the existing user, and we don’t want to delete them. The only difference between the users is their user ID, which we can only get from the response of the API request.

To solve this problem, we can use a recursive function that waits for the API request and checks the user ID. If the user ID is the same as the ID of the existing user, the function calls itself again. If the user ID is not the same, we save the access token and use it to delete the user later.

Here’s the code for the recursive function:

Then inside your test just call the function:

Conditional cy.wait()

Conclusion

By checking the user ID in the response, we can make sure we only delete the correct user. The recursive function approach can be useful when you need to wait for a specific API request and process its response conditionally. And by using a recursive function, you can repeatedly wait for the request until you get the desired response.

If you have a similar problem or need help implementing this solution, feel free to leave a comment.

--

--

Ajdin Mustafic
Ajdin Mustafic

Written by Ajdin Mustafic

Quality Assurance Engineer | Cypress Automation Enthusiast

No responses yet