Assertions
- 13 minutes to read
Use Assertions to verify page action results. Assertions are comparisons that help you determine if the page state is correct. Assertions compare the actual value of a page-related variable to the value you expect it to have. If an assertion fails, the test fails too.
You cannot record assertions.
Test Scripts
The t.expect
TestController method executes assertions like so:
await t.expect( actual ).eql( expected, message, options );
The TestCafe framework documentation includes an assertions guide.
Codeless Tests
The Assertions section of the Actions panel contains assertion templates.
Assertion Parameters
Assertion Target
- If the
DOM
tab is active, the assertion examines a page element that corresponds to an element selector; - If the
fn
tab is active, the assertion examines the return value of a client function.
Element Selector
Create a new Element Selector query in one of two ways:
- Pick the target element with the element picker. TestCafe Studio generates a set of selectors for the target element. To view available selectors, click the button next to the Element Selector input field.
Note
The element picker is available only during recording.
- Use the element selector creation dialog.
Select the property you want to include in the comparison from the Verified Property dropdown. See Element Properties for the list of available properties.
Client Function Return Value
Select a function to execute from the Function drop-down list. The Function drop-down menu contains functions that you defined earlier in the test.
Expected Value
Many assertions compare the results of their evaluations to the value of the Expected Value parameter. You can either manually set the parameter’s value, or click the button to populate the field with the current value of a page element parameter.
Note
- Enclose strings in quotes: write “Thank you, Peter” instead of Thank you, Peter.
Automatic assertion evaluation (recording mode only)
When you add an assertion to your test during recording, TestCafe Studio immediately performs the calculations necessary to execute that assertion. This data may help you pick the right value for the expected value field.
If the assertion you added refers to a page element, TestCafe Studio evaluates the properties of that element, and displays them:
- in the property grid;
- in the Actual Value field next to the Verified Property field.
If the assertion you added refers to a client function, TestCafe Studio automatically evaluates the function in question, and populates the Actual Value field with the result.
Assertion Options
You can configure assertions with the following options:
Timeout - success time limit (in milliseconds). TestCafe repeats the assertion until either the assertion succeeds or the time runs out. TestCafe Studio evaluates the assertion target anew with each attempt.
Access the Record Configuration and Run Configurations dialogs to set the default Assertion Timeout value.
To customize the timeout of an individual assertion, click the Add Timeout button in the assertion parameters area.
See also: Wait for Assertions to Pass
Message - the message to output in case of test failure. To add this option, click the Add Message button in the assertion parameters area.
Assertion Status
TestCafe Studio displays an Assertion Status indicator when it executes an assertion in recording mode.
The Assertion Status indicator can display the following information:
- Success: the assertion passed;
- Failure: the assertion failed;
- Unknown: the assertion has not been executed;
- Ongoing: the assertion is in progress.
Click the Assertion Status indicator to execute the assertion again after you make changes.
Assertion Types
Deep Equal
Asserts that a verified value is equal to an expected value.
For example, the following assertion verifies if the number of label elements on a tested page is equal to 9:
Warning
The Deep Equal assertion takes into account whitespace characters like newline symbols or tabulations when it compares strings. Specify these characters in the Expected Value field (for instance, \n
) or use the Contains and Match assertions to compare only visible symbols.
Not Deep Equal
Asserts that a verified value is not equal to an expected value.
For example, the following assertion checks if the number of label elements on a tested page is not equal to 10:
Ok
Asserts that a verified value is true. You can use this assertion to verify if the element exists, if it is visible, or if it is focused.
For example, the following assertion checks if the Submit button is visible:
Not Ok
Asserts that a verified value is false. You can use this assertion to check if the element does not exist, is not visible, or is not focused.
For example, the following assertion checks if the Submit button does not exist:
Contains
Asserts that a verified value contains an expected value.
For example, the following assertion checks if the input #developer-name
contains the text Peter:
Not Contains
Asserts that a verified value does not contain an expected value.
For example, the following assertion checks if the input #developer-name
does not contain the text John:
Type of
Asserts that a verified value (an element or its attribute) is the type specified in the Type Name field.
For example, the following assertion checks the type of the element’s value
property:
Not Type of
Asserts that a verified value (an element or its attribute) is not the type specified in the Type Name field.
For example, the following assertion checks the type of the element’s visible
property:
Greater than
Asserts that a verified value is greater than an expected value.
For example, the following assertion checks if the element’s ClientWidth
property is greater than 700:
Greater than or Equal to
Asserts that a verified value is greater than or equal to an expected value.
For example, the following assertion checks if the element’s ClientWidth
property is greater than or equals to 700:
Less than
Asserts that a verified value is less than the expected value.
For example, the following assertion checks if the element’s OffsetHeight
property is less than 150:
Less than or Equal to
Asserts that a verified value is less than or equal to an expected value.
For example, the following assertion checks if the element’s OffsetHeight
property is less than or equals to 150:
Within
Asserts that a verified value is within a range from Start Value to End Value. Bounds are inclusive.
For example, the following assertion checks if the element’s ScrollHeight
property is within a range from 100 to 200:
Not Within
Asserts that a verified value is not within a range from Start Value to End Value. Bounds are inclusive.
For example, the following assertion checks if the element’s ScrollHeight
property is within a range from 100 to 200:
Match
Asserts that a verified value matches a specified regular expression.
You can use the following options:
- Global - Performs a global match.
- Sticky - Performs a sticky search.
- Multiline - Performs a multiline match.
- Unicode - Unicode-related features are enabled.
- Ignore Case - Performs a case-insensitive match.
For example, the following assertion checks if the input #developer-name
contains the text Peter:
Important
When you specify a regular expression in JavaScript code, you should enclose a pattern in forward slashes:
However, in the Regular Expression parameter for the Match and Not Match assertions, you should not use forward slashes:
Not Match
Asserts that a verified value does not match a specified regular expression.
You can use the following options:
- Global - Performs a global match.
- Sticky - Performs a sticky search.
- Multiline - Performs a multiline match.
- Unicode - Unicode-related features are enabled.
- Ignore Case - Performs a case-insensitive match.
For example, the following assertion checks if the input #developer-name
does not contain the text John:
Important
When you specify a regular expression in JavaScript code, you enclose a pattern in forward slashes, as follows:
In the Regular Expression parameter for the Match or Not Match assertion, however, you should not use forward slashes:
Element Properties
When you verify a page element’s state, you create a selector that matches a target element and then select the element’s property from the property grid.
The property grid always contains the General Properties group. If you add an assertion during recording, the property grid can also contain the following groups: CSS Properties, Attributes, Rectangle.
Note
When you add an assertion during recording, the property grid also displays property values.
General Properties
Contains properties that are common across all elements and properties that are specific to the target element.
Property | Type | Description |
---|---|---|
exists |
Boolean | true if at least one matching element exists. |
count |
Number | The number of matching elements. |
focused |
Boolean | true if the element is focused, meaning the document.activeElement property returns this element. |
visible |
Boolean | true if the element is visible, meaning the element does not have display: none or visibility: hidden CSS properties, and has a non-zero width and height. |
checked |
Boolean | For checkbox and radio input elements, their current state. For other elements, undefined . |
childElementCount |
Number | The number of child HTML elements. |
childNodeCount |
Number | The number of child nodes. |
classNames |
Array of String | The list of element classes. |
clientHeight |
Number | The inner height of the element, including padding but not the horizontal scrollbar height, border, or margin. See Element.clientHeight. |
clientLeft |
Number | The width of the left border of the element. See Element.clientLeft. |
clientTop |
Number | The width of the top border of the element. See Element.clientTop. |
clientWidth |
Number | The inner width of the element, including padding but not the vertical scrollbar width, border, or margin. See Element.clientWidth. |
hasChildElements |
Boolean | true if the element has child HTML elements. |
hasChildNodes |
Boolean | true if the element has child nodes. |
id |
String | The element’s identifier. See Element.id. |
innerText |
String | The element’s text content “as rendered”. See Element.innerText. |
namespaceURI |
String | The namespace URI of the element. If the element does not have a namespace, this property is set to null . See Element.namespaceURI. |
nodeType |
Number | The type of the node. See Node.nodeType. |
offsetHeight |
Number | The height of the element including vertical padding and borders. See HTMLElement.offsetHeight. |
offsetLeft |
Number | The number of pixels that the upper left corner of the element is offset by to the left within the offsetParent node. See HTMLElement.offsetLeft. |
offsetTop |
Number | The number of pixels that the upper left corner of the element is offset by to the top within the offsetParent node. See HTMLElement.offsetTop. |
offsetWidth |
Number | The width of the element including vertical padding and borders. See HTMLElement.offsetWidth. |
selected |
Boolean | For an <option> element, indicates if it is currently selected. For other elements, undefined . See HTMLOptionElement. |
selectedIndex |
Number | For a <select> element, the index of the first selected <option> element. For other elements, undefined . See HTMLSelectElement.selectedIndex. |
scrollHeight |
Number | The height of the element’s content, including content that is not visible on the screen due to overflow. See Element.scrollHeight. |
scrollLeft |
Number | The number of pixels that the element’s content is scrolled to the left. See Element.scrollLeft. |
scrollTop |
Number | The number of pixels that the element’s content is scrolled upward. See Element.scrollTop. |
scrollWidth |
Number | Either the width of the element’s content (in pixels) or the width of the element itself, whichever is greater. See Element.scrollWidth. |
tagName |
String | The element’s name. See Element.tagName. |
textContent |
String | The text content of the node and its descendants. See Node.textContent. |
value |
String | For input elements, the current value. For other elements, undefined . |
CSS Properties
Contains the target element’s CSS properties and their computed values.
Attributes
Contains element attributes.
Rectangle
Contains the properties that specify the element’s size and its position relative to the viewport: bottom
, height
, left
, right
, top
, width
.
Examples
Check if an Element Exists
Use the Ok assertion to verify the element’s exists property.
For example, the following assertion checks if the Submit button exists:
Check if an Element is Visible or Focused
Use the Ok assertion to verify the element’s visible or focused property.
Check The Number of Elements
To check the number of elements, use the Deep Equal assertion to verify the count
property.
For example, the following assertion checks the number of label
elements on the page:
You can also check the number of elements in more complex scenarios, for example, when you perform search queries or test table filtering. In these cases, you can use assertions like Greater than, Less than, Within, and so on.
The following assertion verifies if the number of table rows is between 3 and 5:
Check an Element’s Text
Use the Contains or Match assertions to check an element’s text.
For example, to check the text in an <input>
or <textarea>
, verify the element’s value property:
For other elements, you can verify the innerText or textContent property. For example, the following assertion verifies the article header’s text:
Check an Element’s Attribute Value
You can use the Deep Equal, Ok or other assertions to check an element’s attribute value.
To access the element’s attributes, add an assertion during test recording. The attributes are displayed in the property grid’s Attributes category.
For example, the following assertion checks the button’s type
attribute:
Check the Page URL
To check the page URL, define a function that returns the location.href
value and verify this value with a Deep Equal assertion.
Page URL: https://devexpress.github.io/testcafe/example/
getUrl
return window.location.href;
Expected Value: 'https://devexpress.github.io/testcafe/example/'
Check the User Agent
You can obtain the navigator.userAgent
string with a function and use the Deep Equal assertion to verify the value.
getUserAgent
return window.navigator.userAgent;
Expected Value: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.2 Safari/605.1.15'
Verify a Complex Object
Client-side functions allow you to perform complex verifications. This example shows how to verify data from specific table columns.
The tested page contains a Data Grid control. To verify the content in its columns, create a function that obtains data from these columns and pushes these data to an array. The Deep Equal assertion can check this array against the expected data.
Page URL: https://js.devexpress.com
getSalesAmount
const grid = document.querySelector('.dx-datagrid-rowsview');
const rowCount = grid.querySelectorAll('.dx-data-row').length;
const sales = grid.querySelectorAll('td:nth-child(3)');
const customers = grid.querySelectorAll('td:nth-child(7)');
const array = [];
for (let i = 0; i < rowCount; i++) {
array.push({
sales: sales[i].textContent,
customer: customers[i].textContent
});
}
return array;
Expected Value
[
{ sales: '$6,370', customer: 'Renewable Supplies' },
{ sales: '$4,530', customer: 'Apollo Inc' },
{ sales: '$1,110', customer: 'Johnson & Assoc' },
{ sales: '$6,600', customer: 'Global Services' },
{ sales: '$2,830', customer: 'Health Plus Inc' },
{ sales: '$6,770', customer: 'Gemini Stores' },
{ sales: '$1,460', customer: 'Discovery Systems' }
]