Role Constructor

Creates a user role.

Role(url, func(t) [, options])

Important

The login page URL cannot be relative. Use an absolute login page URL when you define a Role.

Parameter Type Description
url String The URL of the login page.
func Function An asynchronous function that authenticates the user.
t Object The test controller used to access test run API.
options Object See Options.
import { Role } from 'testcafe';

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

Use the t.useRole method to activate a Role. Activate the anonymous role to clear the authentication data cache and log the user out of all websites.

Options

options.preserveUrl

Stops TestCafe from navigating away after a Role login.

Enable the preserveUrl option to avoid redirection loops, navigation to outdated cached pages, and loss of query string data (e.g., the session ID).

When TestCafe receives instructions to enable a Role, it saves the URL of the active page. When the log-in process is complete, TestCafe goes back to that URL. Enable the preserveUrl option to stop this behavior, and keep the post-login page open.

import { Role } from 'testcafe';

const role = Role('http://example.com/login', async t => {
    await t
        .typeText('#login', 'username')
        .typeText('#password', 'password')
        .click('#sign-in'); // Opens http://example.com?sessionId=abcdef
}, { preserveUrl: true });  // prevents the automatic re-direction back to http://example.com

fixture `My Fixture`;

test('My test', async t => {
    await t
        .navigateTo('http://example.com/')
        .useRole(role);  // Authenticates the user and **doesn't** open http://example.com/

Default value: false