testcafestudio-401265-test-actions-custom-scripts.md
Warning
Security Note: Do not run scripts from unknown sources: they may contain harmful code.
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
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.
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.
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
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.
To use Node.js core modules in the Run TestCafe Script action’s code, import them with the require function.
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.
You can import third-party modules into the Run TestCafe Script action’s code with the require function.
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.
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
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.
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 |
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.
TestCafe Studio intercepts console output in the script and prints it in the action’s parameters area.
View Code
console.log('Debug info');
console.error('Error message');
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
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();
The following example shows how to retrieve data from REST API with the got module.
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');