Custom Scripts
- 4 minutes to read
WARNING
Security Note: Scripts from unknown sources may contain harmful code. If you receive a script from an untrusted source, do not run it unless you are sure that it is safe to do so.
The Custom Scripts category contains the following action:
Run TestCafe Script
Executes custom JavaScript code in the TestCafe test runner.
Custom scripts allow you to introduce conditional or iterative actions, use third-party Node.js modules and all TestCafe features without converting tests to JavaScript.
WARNING
Use the Run TestCafe Script action for test scenarios that cannot be implemented with other actions.
The action's area contains the code editor with syntax highlighting and autocomplete.
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 API, Node.js core and third-party modules.
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.
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.
Import Node.js Modules
You can import Node.js modules (including core modules) to the Run TestCafe Script action's code with the require
function.
const nanoid = require('nanoid');
const str = nanoid();
await t
.typeText('#developer-name', str)
.click('#submit-button')
.expect(Selector('#article-header').textContent).contains(str);
Node.js modules should be installed locally 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.
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.
() => {
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 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.
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.
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.
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');