TestCafe Authentication: Session Management and User Roles

TestCafe Authentication: Session Management and User Roles

Authentication is one of the most common stumbling blocks in E2E test suites. When every test logs in through the UI, your suite is slow, brittle, and fails whenever the login page has issues. TestCafe's User Roles API solves this properly.

The Problem with Repeated Login

The naive approach: log in at the start of every test. This is slow (login takes 2-5 seconds per test), creates load on your auth system, and means a change to the login flow can break unrelated tests.

A better approach: log in once, save the session, and restore it for each test that needs it. TestCafe calls this User Roles.

TestCafe User Roles

The Role API captures browser state after authentication and restores it for subsequent tests:

import { Role, t } from 'testcafe';

const regularUser = Role('https://example.com/login', async t => {
    await t
        .typeText('#email', 'user@example.com')
        .typeText('#password', 'UserPass123!')
        .click('#login-btn');
    
    // Wait for redirect to confirm login succeeded
    await t.expect(Selector('.user-dashboard').exists).ok();
});

const adminUser = Role('https://example.com/login', async t => {
    await t
        .typeText('#email', 'admin@example.com')
        .typeText('#password', 'AdminPass123!')
        .click('#login-btn');
    
    await t.expect(Selector('.admin-panel').exists).ok();
});

Use roles in tests with t.useRole():

import { Selector, t } from 'testcafe';
import { regularUser, adminUser } from './roles';

fixture('Dashboard Tests')
    .page('https://example.com');

test('Regular user sees their own orders', async t => {
    await t.useRole(regularUser);
    
    const orderCount = Selector('.order-list-item').count;
    await t.expect(orderCount).gt(0);
});

test('Admin user sees all orders', async t => {
    await t.useRole(adminUser);
    
    await t.navigateTo('/admin/orders');
    await t.expect(Selector('.all-orders-table').exists).ok();
});

test('Anonymous user sees login prompt', async t => {
    await t.useRole(Role.anonymous());
    
    await t.navigateTo('/dashboard');
    await t.expect(Selector('#login-form').exists).ok();
});

TestCafe caches the browser state after the role's initialization function runs. Switching roles mid-test restores the cached cookies and local storage for that user — no additional login request.

Roles capture:

  • All cookies set during the initialization function
  • localStorage and sessionStorage state
  • URL-based session context

When you switch roles, TestCafe:

  1. Clears the current session state
  2. Restores the cached state for the target role
  3. Navigates to the current page (or a specified URL)

For JWT-based auth where tokens are stored in localStorage:

const jwtUser = Role('https://example.com/login', async t => {
    await t
        .typeText('#email', 'user@example.com')
        .typeText('#password', 'pass123')
        .click('#login-btn');
    
    // Verify token is stored
    const token = await t.eval(() => localStorage.getItem('authToken'));
    await t.expect(token).ok('Auth token should be set after login');
});

Injecting Cookies Directly

For APIs that set auth via cookies, you can inject cookies without going through the login UI:

import { RequestHook } from 'testcafe';

class AuthCookieHook extends RequestHook {
    constructor(token) {
        super();
        this.token = token;
    }

    async onRequest(event) {
        event.requestOptions.headers['Cookie'] = `session=${this.token}`;
    }

    async onResponse(event) {}
}

const authHook = new AuthCookieHook(process.env.TEST_SESSION_TOKEN);

fixture('Protected Pages')
    .page('https://example.com')
    .requestHooks(authHook);

test('Dashboard loads with injected session', async t => {
    await t.navigateTo('/dashboard');
    await t.expect(Selector('.dashboard-content').exists).ok();
});

This is faster than UI login because there's no browser interaction. Use it when you can generate valid session tokens programmatically (from a test auth endpoint or seed data).

Multi-User Scenarios

Some tests require multiple users to be active — for example, testing real-time features or permissions:

test('Admin can see messages from regular user', async t => {
    // Start as regular user
    await t.useRole(regularUser);
    await t.navigateTo('/messages');
    await t.typeText('#message-input', 'Hello from user').click('#send-btn');
    
    // Switch to admin
    await t.useRole(adminUser);
    await t.navigateTo('/admin/messages');
    
    // Verify admin sees the message
    await t.expect(
        Selector('.message-item').withText('Hello from user').exists
    ).ok();
});

For truly concurrent multi-user scenarios, use TestCafe's concurrent execution with separate browsers. The Role API is for sequential role-switching within a single test.

Handling Token Expiration

If your auth tokens expire during long test runs:

const freshTokenRole = Role('https://example.com/login', async t => {
    await t
        .typeText('#email', 'user@example.com')
        .typeText('#password', 'pass123')
        .click('#login-btn');
}, { preserveUrl: true });

// Refresh roles if tests run for extended periods
// Each Role() call re-authenticates from scratch when the role was created
// more than N minutes ago (implement via a role factory function)

function createFreshRole(email, password) {
    return Role('https://example.com/login', async t => {
        await t
            .typeText('#email', email)
            .typeText('#password', password)
            .click('#login-btn');
    });
}

Fixture-Level Authentication

For test files where every test needs authentication, set the role at the fixture level:

fixture('Authenticated Feature Tests')
    .page('https://example.com')
    .beforeEach(async t => {
        await t.useRole(regularUser);
    });

test('Feature A works', async t => {
    // Already authenticated
    await t.navigateTo('/feature-a');
    // ...
});

test('Feature B works', async t => {
    // Already authenticated
    await t.navigateTo('/feature-b');
    // ...
});

Combining TestCafe with Continuous Monitoring

TestCafe User Roles let you run authenticated test suites efficiently. For ongoing production monitoring of authenticated flows, HelpMeTest runs your critical user journeys continuously — including login and post-authentication workflows — without requiring a Node.js build pipeline or TestCafe installation. Use TestCafe for deep authenticated test coverage in CI; use HelpMeTest to monitor production authentication continuously.

Summary

TestCafe's User Roles API is the right way to handle authentication in E2E tests. Define roles once, reuse them across tests, and let TestCafe manage session state. The result: tests that are faster, more reliable, and independent of each other. For direct session injection without UI login, use the RequestHook API to inject cookies or headers from programmatically generated tokens.

Read more

Start now free