TestComplete Scripting: JavaScript and Python Test Automation
TestComplete supports six scripting languages: JavaScript, Python, VBScript, JScript, C++Script, and DelphiScript. In practice, most teams starting fresh today choose JavaScript or Python. This guide focuses on those two, covering the TestComplete object model, writing maintainable tests, data-driven patterns, and advanced scripting techniques.
The TestComplete Object Model
Before writing a line of code, understand the three main object trees you'll work with.
Sys — The System Object
Sys is the root of the process and window hierarchy on the local machine:
// Access a running process
var process = Sys.Process("MyApp");
// Access a window within a process
var mainWindow = process.Window("TMainForm", "My Application");
// Access a child control
var button = mainWindow.Panel("Panel1").Button("btnSave");Sys is how you interact with desktop applications. You navigate the process → window → control hierarchy.
Browsers — The Web Object
Browsers gives you access to running browser instances:
// Run a URL in Chrome
var browser = Browsers.Item(btChrome);
browser.Run("https://app.example.com");
// Get the current page
var page = browser.Page("https://app.example.com/dashboard");
// Find an element
var header = page.FindElement("h1.page-title");
Log.Message(header.innerText);Aliases — The Name Mapping Tree
Aliases is your object repository — the logical names you assign to UI elements in Name Mapping:
// Instead of navigating the raw hierarchy:
var btn = Sys.Process("MyApp").Window("TForm1").Button(0);
// Use the mapped alias:
var btn = Aliases.MyApp.mainForm.btnLogin;Always prefer Aliases over raw Sys navigation. When element properties change, you fix Name Mapping once — not every test.
JavaScript Test Structure
TestComplete's JavaScript is ECMAScript 5.5 with TestComplete-specific globals added. No ES6 modules, no import/export. Functions in the same script unit are global within the project.
Basic Test Function
function TestLogin()
{
// Setup
Browsers.Item(btChrome).Run("https://app.example.com/login");
var page = Aliases.browser.pageLogin;
// Actions
page.txtUsername.SetText("testuser@example.com");
page.txtPassword.SetText("testpassword");
page.btnLogin.Click();
// Assertions
var dashboard = Aliases.browser.pageDashboard;
aqObject.CheckProperty(dashboard.headingWelcome, "Visible", cmpEqual, true);
aqObject.CheckProperty(dashboard.headingWelcome, "innerText", cmpContains, "Welcome");
// Cleanup
Browsers.Item(btChrome).Close();
}Logging
TestComplete's Log object replaces console.log for test output:
Log.Message("Step completed: user logged in"); // informational
Log.Warning("Element found but state is unexpected"); // warning
Log.Error("Expected element not found"); // marks test failed
// With additional data
Log.Message("Current URL", Browsers.Item(btChrome).Page("*").URL);
// Log an image
Log.Picture(Sys.Desktop.Picture(), "Screenshot at failure point");Log.Error() doesn't stop execution — it records a failure and continues. To stop on error, throw or use Runner.Stop().
Error Handling
function SafeClick(element)
{
try {
if (element.Exists) {
element.Click();
return true;
} else {
Log.Warning("Element not found, skipping click: " + element.MappingObject);
return false;
}
} catch(e) {
Log.Error("Click failed: " + e.message);
return false;
}
}Waiting for Elements
Don't use Delay() in production tests. Use property-based waiting:
// Wait up to 10 seconds for an element to become visible
function WaitForElement(element, timeoutMs)
{
var timeout = timeoutMs || 10000;
var interval = 500;
var elapsed = 0;
while (elapsed < timeout) {
if (element.Exists && element.Visible) {
return true;
}
Delay(interval);
elapsed += interval;
}
Log.Error("Element not found after " + timeout + "ms: " + element.MappingObject);
return false;
}
// Usage
WaitForElement(Aliases.browser.pageResults.tblResults);Or use TestComplete's built-in WaitAliasChild:
// Wait for a child element to appear
var loadingSpinner = Aliases.browser.pageApp.WaitAliasChild("spinnerLoading", 5000);
if (loadingSpinner.Exists) {
// wait for it to disappear
loadingSpinner.WaitProperty("Visible", false, 15000);
}Python Scripting
Python tests in TestComplete use the same object model as JavaScript — Sys, Browsers, Aliases, Log, aqObject. The syntax differs but the API is identical.
def TestLogin():
# Setup
Browsers.Item(btChrome).Run("https://app.example.com/login")
page = Aliases.browser.pageLogin
# Actions
page.txtUsername.SetText("testuser@example.com")
page.txtPassword.SetText("testpassword")
page.btnLogin.Click()
# Assertions
dashboard = Aliases.browser.pageDashboard
aqObject.CheckProperty(dashboard.headingWelcome, "Visible", cmpEqual, True)
aqObject.CheckProperty(dashboard.headingWelcome, "innerText", cmpContains, "Welcome")Python 3 (3.8+) is used for TestComplete Python scripts. Standard library is available. Third-party packages can be installed and imported — TestComplete uses your system's Python installation.
Using External Python Libraries
import json
import requests # requires: pip install requests
def LoadTestData():
response = requests.get("https://api.example.com/testdata")
data = response.json()
return data["users"]
def TestWithExternalData():
users = LoadTestData()
for user in users:
RunLoginTest(user["email"], user["password"])Data-Driven Testing
Excel Data Source (JavaScript)
function RunDataDrivenTests()
{
var driver = DDT.ExcelDriver(
"C:\\TestData\\credentials.xlsx",
"Credentials",
true // first row is header
);
while (!driver.EOF()) {
var email = driver.Value("Email");
var password = driver.Value("Password");
var role = driver.Value("ExpectedRole");
Log.AppendFolder("Testing user: " + email);
RunLoginTest(email, password, role);
Log.PopLogFolder();
driver.Next();
}
DDT.CloseDriver(driver.Name);
}CSV Data Source (Python)
def RunCSVTests():
driver = DDT.CSVDriver("C:\\TestData\\inputs.csv", True, ",")
while not driver.EOF():
url = driver.Value("URL")
selector = driver.Value("Selector")
expected = driver.Value("ExpectedText")
RunContentCheck(url, selector, expected)
driver.Next()
DDT.CloseDriver(driver.Name)Database Data Source
function RunDBTests()
{
var connStr = "Provider=SQLOLEDB;Server=testdb;Database=QAData;Trusted_Connection=Yes;";
var query = "SELECT email, password, expected_role FROM test_users WHERE active = 1";
var driver = DDT.ADODriver(connStr, query);
while (!driver.EOF()) {
RunLoginTest(
driver.Value("email"),
driver.Value("password"),
driver.Value("expected_role")
);
driver.Next();
}
DDT.CloseDriver(driver.Name);
}Page Object Pattern
TestComplete doesn't enforce page objects, but the pattern is just as valid here as in Selenium. Create script modules that encapsulate page interactions.
LoginPage.js:
// LoginPage module - encapsulates login page interactions
var LoginPage = {
navigate: function() {
Browsers.Item(btChrome).Run("https://app.example.com/login");
Aliases.browser.pageLogin.Wait();
},
fillCredentials: function(email, password) {
Aliases.browser.pageLogin.txtEmail.SetText(email);
Aliases.browser.pageLogin.txtPassword.SetText(password);
},
submit: function() {
Aliases.browser.pageLogin.btnLogin.Click();
},
getErrorMessage: function() {
var errorEl = Aliases.browser.pageLogin.divError;
if (errorEl.Exists && errorEl.Visible) {
return errorEl.innerText;
}
return null;
},
loginAs: function(email, password) {
this.navigate();
this.fillCredentials(email, password);
this.submit();
}
};Tests.js:
function TestSuccessfulLogin()
{
LoginPage.loginAs("user@example.com", "validpassword");
// Assert we're on the dashboard
aqObject.CheckProperty(
Aliases.browser.pageDashboard,
"Exists",
cmpEqual,
true
);
}
function TestInvalidPassword()
{
LoginPage.loginAs("user@example.com", "wrongpassword");
var error = LoginPage.getErrorMessage();
aqObject.CheckProperty(error, "length", cmpGreater, 0);
}Working with Dynamic Elements
When elements have generated IDs or dynamic attributes, use FindChildEx instead of Name Mapping:
// Find a table row by cell content
function FindTableRow(table, columnName, cellValue)
{
var rowCount = table.wRowCount;
for (var i = 1; i <= rowCount; i++) {
var cell = table.FindChildEx(
["ObjectType", "rowIndex", "columnName"],
["Cell", i, columnName],
3,
true
);
if (cell.Exists && aqString.Contains(cell.innerText, cellValue)) {
return i;
}
}
return -1;
}
// Find an element by text content in a dynamic list
function FindItemByText(list, targetText)
{
return list.FindChildEx(
["ObjectType", "innerText"],
["ListItem", targetText],
2,
true
);
}Variables and Parameters
TestComplete has three types of variables beyond script variables:
Project variables — persist across test runs, stored in the project:
// Read a project variable
var baseUrl = Project.Variables.BaseURL;
// Write a project variable
Project.Variables.LastRunDate = aqDateTime.Now();Test log parameters — pass values to keyword tests:
// In a script called by a keyword test
function LoginWithParams()
{
// KeywordTests can pass parameters to script functions
var email = CallObjectMethodParameters.Param1;
var password = CallObjectMethodParameters.Param2;
RunLoginTest(email, password);
}Runner variables — used within Keyword Test execution contexts.
Custom Checkpoints
Beyond built-in checkpoints, write assertions using the comparison constants:
// Comparison constants
// cmpEqual, cmpNotEqual, cmpContains, cmpNotContains
// cmpStartsWith, cmpEndsWith, cmpMatches (regex)
// cmpGreater, cmpLess, cmpGreaterOrEqual, cmpLessOrEqual
function AssertElementText(element, expectedText)
{
aqObject.CheckProperty(
element,
"innerText",
cmpContains,
expectedText
);
}
function AssertElementCount(parent, childType, expectedCount)
{
var actual = parent.FindAllChildren(
["ObjectType"], [childType], 3
).Count;
if (actual != expectedCount) {
Log.Error(
"Expected " + expectedCount + " " + childType +
" elements, found " + actual
);
} else {
Log.Message("Element count verified: " + actual + " " + childType);
}
}Reusable Utilities
Build a utility module for common operations:
// Utils.js
var Utils = {
// Take a named screenshot and add to log
screenshot: function(name) {
Log.Picture(Sys.Desktop.Picture(), name);
},
// Wait for URL to contain a pattern
waitForUrl: function(pattern, timeoutMs) {
var timeout = timeoutMs || 10000;
var start = aqDateTime.Now();
while (aqDateTime.TimeInterval(start, aqDateTime.Now()) < timeout) {
var url = Browsers.Item(btChrome).Page("*").URL;
if (aqString.Contains(url, pattern)) return true;
Delay(200);
}
Log.Error("URL did not match pattern '" + pattern + "' within " + timeout + "ms");
return false;
},
// Clear and type into a field
clearAndType: function(element, text) {
element.Click();
Sys.Keys("^a");
Sys.Keys(text);
},
// Generate a random string for test data
randomString: function(length) {
var chars = "abcdefghijklmnopqrstuvwxyz0123456789";
var result = "";
for (var i = 0; i < length; i++) {
result += chars.charAt(Math.floor(Math.random() * chars.length));
}
return result;
}
};Running Specific Tests from Command Line
Target individual test functions when running from CI:
# Run a specific script function
TestComplete.exe "Project.pjs" /run /test:"Script//Tests//TestLogin" /exit
# Run all tests in a project item
TestComplete.exe "Project.pjs" /run /test:"Tests" /exit
# Set a project variable at runtime
TestComplete.exe "Project.pjs" /run /p:var:BaseURL="https://staging.example.com" /exitCommon Scripting Mistakes
Using Delay() instead of waiting for conditions: Fixed by checking element state in a loop or using WaitProperty.
Hard-coded waits after navigation: Pages load at different speeds on different machines. Use page.Wait() or check for a landmark element.
Directly modifying Name Mapping in tests: Name Mapping should be stable. If you find yourself calling NameMapping.ConfigureMapping() from a test, that's a sign your object identification strategy needs work.
Not checking Exists before accessing properties: If an element doesn't exist, accessing its properties throws a runtime error. Always guard with element.Exists in conditional flows.
Using Sys.Desktop.Click(x, y) instead of object clicks: Coordinate-based clicks break when screen resolution or window position changes. Always click on objects, not coordinates.
Summary
TestComplete's scripting is capable but different from web-native tools. The object model (Sys, Browsers, Aliases) takes time to internalize. Once it clicks, the pattern is consistent — desktop and web tests work the same way, error handling is explicit, and the Name Mapping layer handles element brittleness better than raw Selenium.
For JavaScript teams, lean into modules and the page object pattern. For Python teams, the ability to use standard libraries gives you flexibility for test data generation, API validation, and custom reporting. Either way, invest time in Name Mapping quality early — it pays off across hundreds of tests.