Test Actions
The following test actions interact with the page:
The following test actions interact with the browser:
- Navigate to a URL
- Take Screenshots
- Handle Native Dialogs
- Resize Windows
- Manage Multiple Browser Windows
The following test action pauses the test:
How Test Actions Work
Test actions are methods of the test controller object. Test actions are infinitely chainable. Action targets are subject to interaction requirements.
Action Chaining
You can invoke the test controller object for every action or assertion, like so:
await t.click('#id1') //actions
await t.typeText('.input-field-1')
await t.click('#submit')
await t.expect(Selector('#result').textContent).eql('expected text');//assertion
Some people find this syntax more intuitive when they both write and debug tests. Other people prefer to chain method calls and minimize code:
await t
.click('#id1') //actions
.typeText('.input-field-1')
.click('#submit')
.expect(Selector('#result').textContent).eql('expected text');//assertion
You can chain all test controller methods that don’t return a value. Add blank lines between logical parts of the action chain to improve readability.
You cannot chain the following methods (TestCafe v1.18.2):
Interaction Requirements
TestCafe imposes a number of requirements on page action targets to keep action simulation realistic.
The action target must meet the following requirements:
- The target is the root page element or its descendant.
- The target is located in the active browser window or the active
<iframe>
. - The target meets the visibility criteria.
- Another element does not overlap the target as to prevent user interaction (See Treatment of Overlapping DOM Elements).
Important
If the target is located outside the viewport, TestCafe scrolls it into view.
Visibility Criteria
The element is visible
if:
- The value of the element’s
display
property is notnone
- The value of the element’s
visibility
property is nothidden
- The element has a non-zero
width
andheight
Elements that meet the visibility criteria above may still be invisible to the user. The following factors do not influence the element’s visibility status:
- The element’s
z-index
- The element’s
opacity
- The element’s position on the page
Additional requirement for t.typeText
The t.typeText
action can only interact with focused elements. If the target element doesn’t have focus, TestCafe automatically clicks it. If the element doesn’t gain :focus
after the click, the action fails.
Touch Devices
On touch devices, TestCafe emulates touch events instead of mouse events.
Mouse event | Corresponding touch event |
---|---|
mousemove (when you hover or drag) |
touchmove (when you drag) |
mousedown |
touchstart |
mouseup |
touchend |
Page Actions
Click
The following three methods click page elements:
Example
import { Selector } from 'testcafe';
fixture `Example`
.page `https://devexpress.github.io/testcafe/example/`;
test('Click test', async t => {
const selectBasedOnText = Selector('label').withText('I have tried TestCafe');
await t
.click(selectBasedOnText);
});
Press Key
The Press Key action presses a key or key combination.
Example
import { Selector } from 'testcafe';
fixture `Example`
.page `https://devexpress.github.io/testcafe/example/`;
test('Press Key test', async t => {
await t
.click('#tried-test-cafe')
// pressing 'Space' imitates clicking the checkbox again
.pressKey('space')
});
Type Text
The Type Text action types a string into an element. The action can target input
fields, textarea
elements, and elements with the contenteditable
attribute. The action target is subject to additional interaction requirements.
Example
import { Selector } from 'testcafe';
fixture `Example`
.page `https://devexpress.github.io/testcafe/example/`;
test('Type Text test', async t => {
await t
.typeText('#developer-name', 'John Doe');
});
Select Text
The Select Text action selects text box content. The action can only target input
fields, textarea
elements, and elements with the contenteditable
attribute.
Example
import { Selector } from 'testcafe';
fixture `Example`
.page `https://devexpress.github.io/testcafe/example/`;
test('Select Text test', async t => {
await t
.typeText('#developer-name', 'John Doe')
.selectText('#developer-name')
.pressKey('delete');
});
Hover
The Hover action hovers the mouse pointer over page elements.
Example
import { Selector } from 'testcafe';
fixture `Example`
.page `https://js.devexpress.com`;
test('Hover test', async t => {
await t
.hover('.map-container');
});
Scroll
Important
TestCafe automatically scrolls valid off-screen action targets into view. There is usually no need to use the scroll
action. Read Scroll Element Into View for more information.
The Scroll method scrolls the target element (or the document body) to the specified position.
Drag Elements
The following two methods drag elements around the page:
These methods emulate user interaction with draggable elements. Do not use them to select text and perform other complex browser actions.
Example
import { Selector } from 'testcafe';
fixture `Example`
.page `https://devexpress.github.io/testcafe/example/`;
test('Drag test', async t => {
const triedCheckbox = Selector('label').withText('I have tried TestCafe');
await t
.click(triedCheckbox)
.drag('#slider', 360, 0, { offsetX: 10, offsetY: 10 });
});
Upload Files
The following two methods interact with file upload input elements:
File Upload Guide
- Use the t.setFilesToUpload action to populate a
file
type input. - If your application uploads files as soon as you populate the field, you don’t need to take any further action. Otherwise, start the upload manually (for example, click the submit button).
- Use the t.clearUpload action to clear the list of files to upload.
Read the Test File Upload article for more details.
Example
import { Selector } from 'testcafe';
fixture `Example`
.page `https://js.devexpress.com/Demos/WidgetsGallery/Demo/FileUploader/FileSelection/jQuery/Light/`;
test('Upload Files test', async t => {
await t
.switchToIframe('.demo-frame')
.setFilesToUpload('.dx-fileuploader-input', [
// substitute the following string with the path to a local file or multiple files you want to upload
'path/to/file'
]);
});
Work With Iframes
TestCafe intentionally limits its browsing context. When you first load the page, you only gain access to the main window.
Use the switchToIframe
method to access an <iframe>
. Use the switchToMainWindow
method to switch back to the main window.
Example
import { Selector } from 'testcafe';
fixture `Example`
.page `https://js.devexpress.com/Demos/WidgetsGallery/Demo/DataGrid/Overview/jQuery/Light/`;
test('Working With iframe test', async t => {
await t
.switchToIframe('.demo-frame')
.click('.dx-datagrid-group-panel')
.switchToMainWindow();
});
Browser Actions
Navigate to a URL
The Navigate action opens a new URL in the current window.
Example
import { Selector } from 'testcafe';
fixture `Example`
.page `https://devexpress.github.io/testcafe/example/`;
test('Navigate To URL test', async t => {
await t
.navigateTo('https://github.com/DevExpress/testcafe');
});
Take Screenshots
The following two actions take screenshots:
Example
import { Selector } from 'testcafe';
fixture `Example`
.page `https://js.devexpress.com`;
test('Take Screenshot test', async t => {
await t
.takeScreenshot()
.takeElementScreenshot('.map-container');
});
Handle Native Dialogs
TestCafe can interact with browser dialog boxes, such as alert()
and prompt()
.
You can close alert and beforeunload dialogs, as well as respond to confirm and prompt dialogs.
Warning
If you automatically handle dialogs with TestCafe, the browser does not display dialog boxes to the end user.
Use the t.getNativeDialogHistory
method to extract the following information from dialog boxes:
- Dialog type
- Dialog content
- Dialog URL
TestCafe includes dedicated methods that handle native authentication prompts. Read the authentication guide for more information.
Resize Windows
Three TestController methods resize browser windows. Before you add these methods to your test suite, make sure that your testing environment meets the necessary requirements.
- t.resizeWindow resizes the window to match the
height
andwidth
parameters. - t.resizeWindowToFitDevice resizes the window to match the resolution of a mobile device.
- t.maximizeWindow maximizes the browser window. To enter full-screen mode, use the
--start-fullscreen
CLI flag.
Browser windows retain their size in between tests and fixtures. You can use hooks to reset window size before or after test entities.
Requirements
You cannot resize the windows of remote browsers.
- Mac testing environments are compatible with window resizing actions out of the box.
- Windows testing environments require .NET 4.0 or newer.
- Linux testing environments require an ICCCM/EWMH-compliant window manager.
Example
import { Selector } from 'testcafe';
fixture `Example`
.page `https://js.devexpress.com`;
test('Resize Window test', async t => {
await t
.resizeWindowToFitDevice('iphonexr')
.maximizeWindow();
});
Manage Multiple Browser Windows
TestCafe v1.10.1 introduced the ability to run multi-window tests in select browsers. Read the Multiple Windows Guide to learn more.
Wait
The Wait action pauses the test.
Warning
Do not use the wait
action to wait for an element to appear.
See Built-In Wait Mechanisms.
Example
import { Selector } from 'testcafe';
fixture `Example`
.page `https://js.devexpress.com`;
test('Wait test', async t => {
await t
.hover('.map-container')
.wait(1000);
});
Recipes
Download Files in IE
To download files in Internet Explorer, you need to manually process unskippable native dialogs.
Consider the following markup:
<body>
<form method="get" action="./src/file.zip">
<button id="downloadButton" type="submit">Download!</button>
</form>
</body>
This page includes a button that triggers a file download. To skip the native dialog in IE, and successfully download the file, use a RequestLogger:
import { RequestLogger } from 'testcafe';
const fileDownloadLogger = RequestLogger(new RegExp('src/file.zip'), {
logResponseBody: true,
stringifyResponseBody: true
});
fixture `fixture`
.page `./fileDownload.html`
.requestHooks(fileDownloadLogger);
test(`Download a file and verify contents`, async t => {
await t
.click('#downloadButton')
.expect(fileDownloadLogger.contains(r => {
return /File contents here/.test(r.response.body) && //verify response body
r.response.statusCode === 200; //verify response status code
})).ok()
});
We know the location of the target file, so we can monitor requests to that file with a RequestLogger
, and verify the response with a regular expression.
Note
Server responses are binary. Use the RequestLogger
‘s stringifyResponseBody option to decode them.
Scroll Element into View
TestCafe scrolls to reach items that are on the page but outside the user’s viewport.
You can use any action (for example, hover) to scroll towards the desired part of the page.
If you specifically need to scroll the page without any action, use the scroll action.
import { ClientFunction } from 'testcafe';
const scrollBy = ClientFunction(() => {
window.scrollBy(0, 1000);
});
test('Test', async t => {
await scrollBy();
});