Authentication and Roles

You can use regular TestCafe actions to log users in and out:

test('log-in and do stuff', async t => {
    await t
        .typeText('#email', 'example@example.com')
        .typeText('#password', 'myPassw0rd')
        .click('button[title="Log In"]');
        // the test continues
});

As your test suite grows, you might prefer to use User Roles — an easier way to manage user authentication.

TestCafe includes dedicated methods for HTTP Basic and Windows (NTLM) authentication. Read the corresponding section for more information.

User Roles

Use Roles to log users in and out with a single line of code.

Quick Guide

  1. Create a Role definition with authentication actions.
import { Role } from 'testcafe';

const userOne = Role('http://example.com/login', async t => {
    await t
        .typeText('#login', 'TestUser')
        .typeText('#password', 'testpass')
        .click('#sign-in');
});

See: Create Roles

  1. Call the t.useRole method to activate a Role, and log the user in.
    await t.useRole(userOne)

See: Activate Roles

  1. Optional. Activate another Role (for example, the built-in Anonymous Role) to log the user out.
   await t.useRole(Role.anonymous());

See: Log out

Why use Roles

  • Ease of use. Switch between user accounts with a single method call.
  • Cleaner code. Role definitions let you separate authentication logic from the rest of code. This makes your test suite easier to maintain.
  • Faster test execution. TestCafe only executes the log-in routine once in each of the browsers you open. During subsequent Role activations, TestCafe re-uses Role authentication data (cookies and other artifacts) to instantly log users in and out.
  • One Role for many websites. The active Role saves all the authentication data that the browser receives. You can enable a Role, and then log into as many websites as you want. When you next activate that Role, you’ll log back into all these websites.
  • Seamless authentication. Login actions do not interrupt your test scenario. When TestCafe activates a Role, it automatically navigates to the log-in page, and goes back when the log-in process is complete. The preserveUrl option disables this behavior.
  • No manual log-outs. TestCafe automatically empties authentication data cache when you switch to a new Role. Activate the Anonymous Role to log everyone out.
  • Object-based API. Role objects store both the authentication data and the associated logic. You can access these objects anywhere in code.

Authentication solutions that rely on page models and helper functions do not offer such advanced capabilities.

How Roles Work

TestCafe only executes log-in routines once per browser per test run. During subsequent Role activations, TestCafe does not perform authentication actions — it just retrieves the authentication data.

While the Role is active, TestCafe saves the authentication data from cookie storage, localStorage, and sessionStorage to the active Role object. If your web application stores authentication data elsewhere, TestCafe cannot save it.

TestCafe does not limit the amount of authentication data that a single Role can store. If you activate a Role, and then log into multiple websites, that Role will store all the authentication data that the browser receives. Subsequent Role activations will log you into multiple websites.

Create Roles

The Role constructor creates Roles. It takes two arguments: a string with the log-in page URL, and an asynchronous function with sign-in actions.

Important

Set the baseUrl option to use a relative login URL.

import { Role } from 'testcafe';

const userOne = Role('http://example.com/login', async t => {
    await t
        .typeText('#login', 'TestUser')
        .typeText('#password', 'testpass')
        .click('#sign-in');
});

You can share Roles across tests and fixtures. Define Roles in a separate helper file, and use them in any test fixture that references this file.

Activate Roles

You can activate Roles anywhere in the test body. Role definitions cannot contain Role activations. To activate a role, use the t.useRole method.

The first time you activate a role, TestCafe navigates to the login page and executes login actions. When the authentication is complete, TestCafe goes back to the page that was open before Role activation. Use the preserveUrl option to disable this behavior.

When you activate a role for the second time, TestCafe does not navigate to the login page. It just loads the Role authentication data and refreshes the current page. See: How Roles Work

import { Selector } from 'testcafe';

fixture `My Fixture`
    .page `http://example.com`;

test('test with two users', async t => {
    await t
        .useRole(regularUser)
        .click('#delete-button')
        .useRole(administrator)
        .click('#delete-button');
});

We recommend that you activate Roles within before and beforeEach hooks. That way, TestCafe gathers Role authentication data at the very beginning of the test suite, and all subsequent activations happen instantaneously.

Log out

You don’t need to add log-out actions to your tests. The Anonymous role empties the authentication data storage, and logs you out of all websites. To activate the Anonymous role, pass the Role.anonymous() function to the useRole method.

import { Selector, Role } from 'testcafe';

fixture `My Fixture`;

test('Anonymous users can view new comments', async t => {
    await t
        .useRole(registeredUser)
        .navigateTo('http://example.org')
        .typeText('#comment', 'Hey ya!')
        .click('#submit')
        .useRole(Role.anonymous());

    const comment = await Selector('#comment-data');

    await t.expect(comment.innerText).eql('Hey ya!');
});

Role limitations

  • TestCafe does not share Role authentication data between browsers.

  • TestCafe does not share Role authentication data between different test runs. TestCafe empties the authentication data storage when the test run ends. The next time you run TestCafe and activate a Role, TestCafe repeats the authentication process.

  • Roles remain active until the user activates a different Role, or the test ends. To continue using the same Role in the next test, you need to activate it again.

  • The active Role saves all the authentication data that the browser receives. You can enable a Role, and then log into as many websites as you want. When you next activate that Role, you’ll log back into all these websites. For instance, imagine that Role A contains authentication code for website #1. If you enable it, and then log into website #2, Role A will save authentication data for both websites.

Failed logins

Don’t use Roles to deliberately enter invalid login information. If you want to test an application’s response to login failure, add log-in actions to the test body.

Roles simply save and load authentication data. They cannot confirm the presence or the validity of authentication data. If your log-in fails and you receive no cookies, subsequent Role activations will not authenticate the user and will yield test errors.

HTTP Authentication

Important

When TestCafe uses native automation, it cannot authenticate users with the NTLM protocol.

TestCafe can open web pages that require HTTP Basic and Windows (NTLM) authentication.

Use the test.httpAuth method to specify credentials for each test, and the fixture.httpAuth method to specify credentials for the entire fixture.

Browsers do not display native browser authentication prompts when TestCafe authenticates the user.

fixture `My fixture`
    .page `http://example.com`
    .httpAuth({
        username: 'username',
        password: 'Pa$$word',

        // Optional parameters; can be required for NTLM authentication.
        domain:      'CORP-DOMAIN',
        workstation: 'machine-win10'
    });

test('Test1', async t => {});          // Logs in as username

test                                   // Logs in as differentUserName
    .httpAuth({
        username: 'differentUserName',
        password: 'differentPa$$word'
    })
    ('Test2', async t => {});

Troubleshooting

Test Actions Fail After Authentication

Some tests fail when you return to a cached page after a login.

Throughout the test, TestCafe regularly updates client-side automation scripts. Navigation to a cached page that contains outdated automation scripts may break TestCafe. You may also lose authentication data, as well as data from local or session storage.

If tests fail unexpectedly after authentication, try the following:

  • Enable the preserveUrl option to disable automatic navigation.
  • If preserveUrl does not fix the issue, disable page caching. Note that this slows down test execution.

Use fixture.disablePageCaching or test.disablePageCaching to disable caching during a fixture or test:

fixture
    .disablePageCaching `My fixture`
    .page `https://example.com`;
test
    .disablePageCaching
    ('My test', async t => { /* ... */ });

To disable page caching during the entire test run, use one of the following options: