Skip to content
Advertisement

Cypress: Re-use auth token across multiple API tests

I have a Rest API which generates a token. This session token is used across multiple REST API’s as an authorization Bearer token. I used this as reference: https://github.com/cypress-io/cypress-example-recipes/blob/master/examples/logging-in__jwt/cypress/integration/spec.js

However, in that example, the function to generate token is embedded in the test. I tried to create a custom command for which should store locally but it is not being picked up by the test. Note that no return value is included in the custom command.

My code below under support/commands.js:

JavaScript

My test:

JavaScript

When I run the test, the log shows null value for ‘identity’. However, it shows the current value in the custom command where I placed cy.log(identity.access_token) I tried using cy.writeFile but I don’t think this is a clean method. There must be some way data can be passed between functions, and different classes.

Sample JSON format:

JavaScript

Advertisement

Answer

You can use the cypress-localstorage-commands package to persist localStorage between tests.

In support/commands.js:

JavaScript

Inside your tests:

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement