How to define a Role without login page in TestCafe?

Viewed 360

I'm having trouble to make my tests stable with this code. Can someone give me some directions

My app doesn't have a login page, and users might get logged in different ways, what determines if they're clogged or not is an auth cookie.

So I decided to define a role by a direct API call to the authentication API then save a cookie with the user token:

export const adminUser = Role('any-page', async t => {
  const loginRequest = await fetch(
    `https://my-auhtentication-api/oauth/token?grant_type=password&username=${userName}&password=${password}`,
    {
      method: 'POST',
    }
  )
  const loginToken = await loginRequest.json()
  await ClientFunction(() => {
    document.cookie = `myAuthCookie=${loginToken.access_token}; Domain=.my-app-domain.com; Path=/`
  })
})

And then I use in my code test like this:

fixture('[Admin User] Menu navigation')
  .beforeEach(async t => {
    await t
      .useRole(adminUser)
      .navigateTo(strictPage)
  })

The problem is that it works fine when I run only this test, but when I run it with the rest of my stack it becomes very unstable, sometimes works, sometimes not.

1 Answers

For end-to-end tests, it's better if your test environment is the same as your production environment. Your comment indicates that you use a parent web app to authenticate your users in the production environment, so the best way to test authentication is using the same parent app in your test environment.

Related