Cypress: How to retrieve data from API request which is written inside a function ?

Gurudatt S A
1 min readAug 9, 2022

--

Cypress uses command chaining to retrieve the data yielded from previous function and using local variables isn’t the best way when you want to retrieve certain values from webpage or API response to store and pass it to next functions.

There are two ways to that, one is wrap the value inside the “then” command as alias and then retrieve using get or use the mocha’s context for storing it in ‘’this” object context. The latter won’t work if our code is written as class function or separate function outside Mocha’s test context.

Below is an example where the API request is written inside a separate class function — the function retrieves the accesToken from response and wraps it to an alias and return that alias

Further we can use that return object to chain it with “then” in our test and proceed with next set of operations.

--

--

Gurudatt S A

Cypress Ambassador, BrowserStack Champion and Test Automation Enthusiast