0
votes

So I am writing e2e automation tests using Cypress. In an effort to keep my tests atomic I try to generate required data for THAT specific test.

So for example I try to start out with a clean database (with migrations ran) and generate a user via the Cypress API request.

The problem is using devise-jwt I need to send along the auth: bearer token along with it. Usually this is generated on sign-in. So there-in lies the problem: To make a POST request to create a user, I need to have the token to authenticate....but without a user to sign in as and grab the token I can't know what the token is going to be.

I hate to seed the database with just one user, since I am trying to keep dependencies minimal and tests atomic as possible. Is there some way to "grab/generate" the auth token through devise and use that in my test somehow?

This is a Rails/React app fwiw.

1

1 Answers

0
votes

I don't know the workflow for fetching the devise-jwt token, but if it results in a cookie, sessionStorage or localStorage value, you can preserve it with cy.session().

Cypress.config('experimentalSessionSupport', true)

beforeEach(() => {                   
  cy.session('mySession', () => {

    // this "setup" callback is called once only, 
    // thereafter results are returned from cache

    // actions to seed database, get user data

    const window = cy.state('window')
    window.fetch(LOGIN_URL, dataWithLoginInfo).then(response => {
      const jwt = response.headers.get('Authorization').split('Bearer ')[1];
      window.sessionStorage.setItem('jwt', jwt)  // this is now cached - same token each time
    })
  })
})

it('uses jwt token', () => {
  const token =  cy.state('window').sessionStorage.getItem('jwt')
  const headers = { Authorization: `Bearer ${token}` }
  ...
})