Does TestCafe require useRole call in every test/beforeEach
Asked Answered
E

1

6

I've been evaluating TestCafe for an app that requires user authentication. The documentation isn't very clear and I've had trouble getting a straight answer on how we should be using useRole.

Our application requires user authentication, right now we only test a single user so we have no need to switch user sessions.

I've defined a Role and it authenticates correctly. But I've noticed the following:

  1. I need to call useRole first in every test in order to use the authenticated session
  2. Every time useRole is called (first in every test) TestCafe navigates the browser back to the original login URL (or whatever preserveUrl saves post-login)

Are either of these statements wrong? I can't imagine how this works in a real environment, that's an insane amount of redirects.

Item 2 seems correct, a devexpress github contributor replied "Currently, TestCafe can't use a Role without reloading or triggering page navigation" so if I have to call useRole in every test that's literally doubling the HTTP navigation load.

Elvinaelvira answered 28/2, 2019 at 18:54 Comment(0)
B
11

The purpose of useRole is to authenticate to the app only once (per user): this means you will see the login page in the first test, and all other tests will start directly on the App page with the user being already authenticated.

The problem is that every test runs in a sandbox. The sandbox is per test and not per fixture. This means that when a test starts to execute, it starts in a brand new sandbox with no cookies and no local storage.

The only way to re-apply cookies and local storage is to call useRole. This is why useRole must be called at the beginning of each test.

useRole is a huge time saver. When I started to work with TestCafe (more than one year ago) useRole did not exist and each test would start by feeding the login page.

useRole is even more useful when you need to switch, inside a test, between different users.

And then to finish, yes, useRole reloads the App page because each test starts in a sandbox with no page history.

What you are looking for is a feature that does not exist: do not reload page between test. If you do not want to reload the page each time, do all you tests in a single test method.

Brady answered 28/2, 2019 at 21:23 Comment(1)
Thanks I've been digging deeper and testing on a different site I own. What I've realized is I have to manually use navigateTo after useRole as well, because my app redirects anonymous users to a login. So tc starts fresh, gets redirected to login, then refreshes with useRole, but is stuck where it shouldn't be.Elvinaelvira

© 2022 - 2024 — McMap. All rights reserved.