Back to Devexpress

Custom Scripts

testcafestudio-401265-test-actions-custom-scripts.md

latest9.0 KB
Original Source

Custom Scripts

  • Nov 22, 2024
  • 5 minutes to read

Warning

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

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.

View Code

js
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.

View Code

js
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.

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.

View Code

js
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.

View Code

js
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.

View Code

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

await t.addRequestHooks(logger);

t.ctx.logger = logger;
js
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.

View Code

js
() => {
    return 'kebab-case-string';
}
js
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 ItemAPI Object
Element SelectorSelector
FunctionClientFunction

Debug the Script

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

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

You can use the 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 button runs the custom script against the tested page in its current state, as it is displayed in the browser.

Print Debug Information

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

View Code

js
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.

View Code

js
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.

View Code

js
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');