Skip to main content
A newer version of this page is available. .

Custom Scripts

  • 5 minutes to read

Warning

Security Note: Do not run scripts from unknown sources: they may contain harmful code.

Run TestCafe Script icon Run TestCafe Script

Run TestCafe Script

Test scripts take full advantage of the Node.js ecosystem. They can reference third-party JavaScript modules, and use complex internal logic.

The Run TestCafe Script action allows codeless test users to embed custom JavaScript into their codeless tests without adopting the test script workflow.

Warning

Use the Run TestCafe Script action for test scenarios that cannot be implemented with other actions.

The action’s settings area contains a code editor with syntax highlighting and auto-completion.

Run TestCafe Script Action

View Code
const _ = require('lodash');

const actual = _.defaults({ a: 1 }, { a: 3, b: 2 });

await t.expect(actual).eql({ a: 1, b: 2 });

Use the Documentation link to view help for this action.

Write the Script

Scripts in the Run TestCafe Script action can use:

TestCafe executes this script in the server-side test runner. The DOM, browser API, and client-side objects are not available in its context. Use client functions and selectors to obtain data from the DOM.

Note

TestCafe executes the script as an asynchronous function. Add await to all asynchronous calls.

Use TestCafe API

The test controller object is available in the script’s context as t. You can use this object to execute test actions and assertions, attach request hooks, etc.

Use TestCafe API in Custom Scripts

View Code
const logger = RequestLogger('https://example.com');

await t
    .addRequestHooks(logger)
    .expect(logger.requests.length).eql(0);

See the test controller’s member list in TestCafe API reference.

Constructor functions that create TestCafe API objects are imported to the test context. You can use the following functions without require:

Note

TestCafe executes custom scripts as parts of the current test. You cannot use them to declare new tests or fixtures.

Limitations
  • The Visual Test Recorder cannot synchronize the browsing context with Run TestCafe Script action’s code.

    For instance, consider a test with a custom script that uses t.switchToIframe to switch the browsing context. If you try to record new actions in this test, the Recorder does not detect that the context has changed and continues recording in the main window.

    To avoid this, do not switch the browsing context in custom scripts. Use the Switch Frames actions instead.

Use Node.js Core Modules

To use Node.js core modules in the Run TestCafe Script action’s code, import them with the require function.

Import Node.js Modules in Custom Scripts

View Code
const fs = require('fs');

await t.expect(fs.existsSync('./downloaded.pdf')).ok();

The imported modules are not shared between Run TestCafe Script actions. To use the same module in multiple scripts, call require in each script.

Import Third-party Modules

You can import third-party modules into the Run TestCafe Script action’s code with the require function.

Import Node.js Modules in Custom Scripts

View Code
const nanoid = require('nanoid');

const str = nanoid();

await t
    .typeText('#developer-name', str)
    .click('#submit-button')
    .expect(Selector('#article-header').textContent).contains(str);

The modules should be installed in the test directory. TestCafe Studio cannot import globally installed modules.

The imported modules are not shared between Run TestCafe Script actions. To use the same module in multiple scripts, call require in each script.

Script Context

The Run TestCafe Script action runs code in a context that does not include variables declared in the previous scripts.

Use the t.ctx property to share variables between Run TestCafe Script actions.

Share Variables Between Custom Scripts

View Code
const logger = RequestLogger(/devexpress.github.io/);

await t.addRequestHooks(logger);

t.ctx.logger = logger;
await t.expect(t.ctx.logger.requests.length).gt(0);

However, the script’s context includes element selectors and functions declared in the Define Element Selector and Define Function actions.

Access Functions From Custom Scripts

View Code
() => {
    return 'kebab-case-string';
}
const _ = require('lodash');

const actual = _.camelCase(await getData());

await t.expect(actual).eql('kebabCaseString');

Element selectors and functions are represented with the following objects:

Test Item API Object
Element Selector Selector
Function ClientFunction

Debug the Script

Click the Run Script Run script button to execute the script during recording.

Run Custom Script

You cannot run a script when a different script is executed, or an assertion is evaluated.

You can use the Run Script Run script button to debug scripts in a hook when the Recorder stops inside this hook because of a failed action or error. In this instance, you cannot run scripts in the test until the Recorder completes playing back the hook.

Note

The Run Script Run script button runs the custom script against the tested page in its current state, as it is displayed in the browser.

TestCafe Studio intercepts console output in the script and prints it in the action’s parameters area.

Output Debugging Information From Custom Scripts

View Code
console.log('Debug info');
console.error('Error message');

Examples

Check if a File Was Downloaded

The following example shows how to check if a file was downloaded. This example uses the path and fs modules to calculate file paths and access the file system.

Check if a File Exists

View Code
const fs   = require('fs');
const path = require('path');

const DOWNLOAD_DIR = path.join(process.env.HOME || process.env.USERPROFILE, 'downloads/');
const file_path    = path.join(DOWNLOAD_DIR, 'image.png');

await t.expect(fs.existsSync(file_path)).ok();

Fetch Data From REST API

The following example shows how to retrieve data from REST API with the got module.

Fetch Data From REST API

View Code
const got = require('got');

const url      = 'https://reqres.in/api/users/2';
const { body } = await got(url, {
    responseType: 'json'
});

const parsedBody = JSON.parse(body);

await t.expect(parsedBody.data.first_name).eql('Janet');