Table of Contents
Squish assumes that all test.js
files use
the UTF-8 encoding. If you expect to edit such files outside of the
Squish IDE, make sure that the editor loads and saves the files using UTF-8.
In theory, any JavaScript book or online resource
is suitable for learning about the language or for looking up functions.
Unfortunately most authors don't make a clear distinction between
features that are part of the JavaScript language itself and
browser-specific extensions. When reading such texts beware of any
example code that makes use of the window
or
document
objects since these are provided by browsers
and are not part of the language.
By keeping in mind the distinction between the pure language (which is what Squish supports) and browser-specific extensions, you'll be able to find the information you need from a variety of books and online resources while avoiding confusion. Here are some useful online JavaScript language resources:
Mozilla's Core JavaScript Reference
Microsoft®'s JScript Language Reference at msdn.microsoft.com
DevGuru JavaScript Quick Reference at www.devguru.com
If you prefer books, a good JavaScript book is JavaScript: The Definitive Guide by David Flanagan.
The JavaScript engine shipped with Squish is based on the ECMAScript language specification (ECMA 262 Edition 3, plus parts of later editions). The language core that is defined in this standard encompasses operators, control structures, objects, and other features commonly found in a scripting language. The subset of supported built-in classes and members can be found in Squish ECMAScript Support (Section 6.16.3).
The pure JavaScript (i.e., ECMAScript) language has no built-in support for file handling or networking, unlike other scripting languages such as Python and Tcl. This is because JavaScript has been designed to be a small language that can be safely embedded into applications. However, JavaScript is also designed to be extened by custom APIs specific to the embedding application. In the case of web browsers there are hundreds of functions and properties that allow for the manipulation of HTML documents via the DOM API, for example. In the case of Squish we have added numerous functions specific to testing. And we have also added some general purposes classes described below. And if the features we have added are not sufficient for your needs contact support and request an enhancement.
![]() | Backslashes in Strings |
---|---|
Some JavaScript functions take a path parameter. This can be a directory
or a filename (and can include the full path), such as |
Table of Contents
This section is about the ECMAScript API subset that is supported in Squish. Squish also adds non-standard objects like File, XML and SQL, and a testing-specific API which are described in other sections of JavaScript Notes and Extension APIs (Section 6.16).
as
,
break
,
case
,
catch
,
const
,
continue
,
default
,
delete
,
do
,
else
,
export
,
extends
,
false
,
finally
,
for
,
from
,
function
,
if
,
in
,
instanceof
,
import
,
let
,
new
,
null
,
of
,
return
,
static
,
super
,
switch
,
this
,
throw
,
true
,
try
,
typeof
,
var
,
void
,
while
,
with
{
, }
,
(
, )
,
[
, ]
,
.
, ,
, ;
<
, >
,
<=
, >=
,
==
, !=
,
===
, !==
,
+
, -
,
*
, /
, %
,**
,
++
, --
,
<<
, >>
, >>>
,
&
, |
, ^
,
!
, ~
,
&&
, ||
,
??
, ...
?
, :
, =
,
+=
, -=
,
*=
, /=
,
%=
, **=
,
<<=
, >>=
,>>>=
,
&=
, |=
,^=
,
&&=
, ||=
,
??=
and =>
.
NaN
Infinity
undefined
decodeURI()
decodeURIComponent()
encodeURI()
encodeURIComponent()
escape()
eval()
isFinite()
parseFloat()
parseInt()
unescape()
Array
Boolean
Date
Error
Function
Map
Number
Object
RegExp
Set
String
EvalError
RangeError
ReferenceError
SyntaxError
TypeError
URIError
JSON
Math
concat()
every()
filter()
forEach()
indexOf()
join()
lastIndexOf()
map()
pop()
push()
reduce()
reduceRight()
reverse()
shift()
slice()
some()
sort()
splice()
toLocaleString()
toString()
unshift()
getDate()
getDay()
getFullYear()
getHours()
getMilliseconds()
getMinutes()
getMonth()
getSeconds()
getTime()
getTimezoneOffset()
getUTCDate()
getUTCDay()
getUTCFullYear()
getUTCHours()
getUTCMilliseconds()
getUTCMinutes()
getUTCMonth()
getUTCSeconds()
getYear()
setDate()
setFullYear()
setHours()
setMilliseconds()
setMinutes()
setMonth()
setSeconds()
setTime()
setUTCDate()
setUTCFullYear()
setUTCHours()
setUTCMilliseconds()
setUTCMinutes()
setUTCMonth()
setUTCSeconds()
setYear()
toDateString()
toGMTString()
toISOString()
toJSON()
toLocaleDateString()
toLocaleString()
toLocaleTimeString()
toString()
toTimeString()
toUTCString()
valueOf()
E
LN10
LN2
LOG10E
LOG2E
PI
SQRT1_2
SQRT2
abs()
acos()
asin()
atan()
atan2()
ceil()
cos()
exp()
floor()
log()
max()
min()
pow()
random()
round()
sin()
sqrt()
tan()
toExponential()
toFixed()
toLocaleString()
toPrecision()
toString()
valueOf()
create()
defineProperties()
defineProperty()
freeze()
getOwnPropertyDescriptor()
getOwnPropertyNames()
getPrototypeOf()
is()
isExtensible()
isFrozen()
isSealed()
keys()
preventExtensions()
seal()
setPrototypeOf()
eval()
hasOwnProperty()
isPrototypeOf()
propertyIsEnumerable()
toLocaleString()
toString()
valueOf()
__defineGetter__()
__defineSetter__()
fromCharCodeAt()
anchor()
big()
blink()
bold()
charAt()
charCodeAt()
concat()
endsWith()
fixed()
fontcolor()
fontsize()
includes()
indexOf()
italics()
lastIndexOf()
link()
match()
repeat()
replace()
search()
slice()
small()
split()
startsWith()
strike()
sub()
substr()
substring()
sup()
toLowerCase()
toString()
toUpperCase()
trim()
trimLeft()
trimRight()
valueOf()
The File
object provides basic file handling functions such
as checking for a file's existence, opening a file for reading or
writing, and removing a file. In general paths that include directories
can be separated using /
(which doesn't need escaping),
even on Windows.
Example:
var file = File.open("C:\\testdata\\input.txt", "r"); file.encoding = "system"; // Should only be needed for some Windows AUTs var text = file.read(); inputField.setText(text);
The default file encoding is "utf-8"
which is the best
encoding to use for text files.
Here are some quick links to the File
object's properties
and methods.
This method closes the file object it is called on. Once closed a file object cannot be read from or written to.
This function copies the file source
to target
. If this fails an exception is
thrown.
The copy fails if target
already exists. If
desired, File.remove
can be used
beforehand to make room for the copy.
This property defines the encoding to use when reading or writing files. The
default encoding is "utf-8"
. For AUTs that don't support UTF-8
(such as some Windows applications), setting the encoding to
"system"
may prove helpful since this makes Squish use the
current system locale. Other possible values are "ucs-2"
(2 byte
Unicode, for reading UTF-16 on Windows) and "latin1"
(also known as
ISO 8859-1) which includes the US-ASCII range.
This property should be set before doing any reading or writing.
This function returns true
if the specfied
fileOrDirectory
exists; otherwise it returns
false
. The fileOrDirectory
may
include an absolute or relative path, or no path, in which case the
current working directory is used.
File File.open(
fileName, mode)
;
This function tries to open the specified
fileName
(which may include an absolute or
relative path, or no path, in which case the current working directory
is used). The optional mode
parameter defaults to
"r"
(open for reading). If the
mode
is specified it must be:
"a"
(open for append), or
"r"
(open for reading), or
"w"
(open for writing).
If the fileName
cannot be opened a catchable
exception is thrown.
Once a file has been successfully opened its methods can be called. For
files opened in append or write mode the file.write
method can be called, and for files
opened in read mode the file.read
and
file.readln
methods can be called. And for
any opened file, the file.close
method can be
called.
This function returns the list of paths matching any of the given patterns.
This method reads in the entire contents of the file object returned
by the File.open
function—providing the file was opened in read mode. The file's
content is assumed to be plain text using the UTF-8 encoding (unless the
file.encoding property is changed).
This method reads in the next line from the file object returned
by the File.open
function—providing the file was opened in read mode. The file's
content is assumed to be plain text using the UTF-8 encoding (unless the
file.encoding property is changed). Each line
is returned without any end of line characters, and if an attempt to
read beyond the last line is made, null is returned.
This function tries to remove the specified
fileName
(which may include an absolute or
relative path, or no path, in which case the current working directory
is used). If the file was successfully removed the function returns
true
; otherwise it returns false
.
The global File
object's read-only separator
property
holds the file separator used by the operating system. For example, on
Windows it holds, "\"
, and on Unix-like systems,
"/"
.
This function returns the size of the specified
fileName
(which may include an absolute or
relative path, or no path, in which case the current working directory
is used).
This method writes the given string
to the file
object returned by the File.open
function—providing the file was opened in append or write mode.
The string
is written using the UTF-8 encoding
(unless the file.encoding property is
changed).
The console
object provides functions for basic interaction
with script execution. The console
object is not a standard
JavaScript object, but is well known from web browsers.
Here are some quick links to the console Object's methods:
If the first parameter is evaluated to false the script execution will be stopped and an error message is written to the test results, otherwise nothing will happen. The second parameter is optional and allows writing user specified message to the test result.
Here is an example that shows the usage of this function:
var index = findIndexOfSomething( "something" ); Console.assert( index >= 0, "Something not found, execution aborted!" ); something[ index ].doSomething();
The OS
object provides functions for basic interaction with
the operating system. It includes functions for executing commands
(i.e., for running programs), for getting and setting the current
directory, and for getting and setting environment variables.
Here are some quick links to the OS Object's properties and methods:
The OS
object's read-only argv
property holds the
absolute filename to the current test script followed by the list of script
arguments passed to squishrunner (see also
squishrunner (Section 7.4.3)).
Here is an example that shows how to read an optional script argument:
var filename = "defaultfile.txt"; if (OS.argv.length > 1) { filename = OS.argv[1]; }
This function executes the given command
in a
shell (console) just like the OS.system
function. The command
string must hold the name of
the command to be executed, and may optionally include command line
arguments and shell redirection characters.
What makes this function different from the OS.system
function is that it captures the
command's output, that is, any text that would normally go to the
console (the stdout
stream), and returns it as a string.
Here is an example that shows the execution of a command on Windows, and the capturing of its output:
var files = OS.capture("dir C:\\temp\\*.dat").split('\n'); for (var i in files) { var file = files[i]; // ... }
Note that in this particular case it is easier and better to use the
cross-platform OS.listDir
function to
get a list of files in a directory.
This function changes the test script's current working directory to the
specified path
.
Example:
var path = OS.cwd() + "/results"; OS.chdir(path);
This function returns the current working directory as a string.
Example:
var path = OS.cwd(); test.log("Current working directory: " + path);
This function returns the value of the environment variable with the
given name
, or an empty string if no such
environment variable exists. (See also, OS.setenv
.)
Example:
var homeDir = OS.getenv("HOME"); test.log("Current user's home directory: " + homeDir);
This function returns a list of all the files and directories in the
directory specified by path
, but excluding the
special directories .
(current) and
..
(parent). This function does not recurse into
subdirectories.
Here is an example that logs all the files that were generated in an output directory on Windows:
var files = OS.listDir("C:\\temp\\output"); for (var i in files) test.log("Found generated file: " + files[i]);
The OS
object's read-only machine
property
holds the name of the machine's hardware that squishrunner is
running on. On Microsoft® Windows systems the value is either "x86",
"amd64", "arm64" or "ia64". On Unix-like systems the value is the same as the
output of uname -m
, e.g. "i686", "x86_64", etc.
The OS
object's read-only name
property holds
the name of the operating system that squishrunner is running on. On
Microsoft® Windows systems the value is "Windows". On Unix-like systems
the value is the same as the output of uname -s
, e.g.
"Linux", "Solaris", "Darwin", etc.
This function pauses the script for the specified number of
milliseconds. Unlike the snooze
function,
the delay is fixed and not influenced by the current
snooze factor setting.
This function deletes the directory found at path
including all of its contents. The function returns
true
on success and in case the directory did not
exist in the first place. (The desired result was still achieved.)
Example:
OS.system("mkdir exampleDir"); var file = File.open("exampleDir/data", "w"); file.write("some data"); file.close(); var result = OS.removeRecursively("exampleDir"); test.log("Deletion result: " + result);
This function deletes the directory found at path
. It
must be empty at the time of deletion. On success, the function returns
true
.
Example:
var oldDir = "C:\\build_old"; var result = OS.rmdir(oldDir); test.log("Deletion result: " + result);
This function creates the directory with the path path
,
if the path is absolute and with the path current_directory/path
,
if the path is relative.
IMPORTANT: all necessary directories mentioned in path
will be created, if they don't already exist.
The function throws an error in case:
(a) call arguments are wrong; or
(b) directory already exists; or
(c) creating directory failed for any other reason like I/O error.
If successful, function returns true
.
Example:
var Dir = "C:\\some_new_directory"; var result = OS.mkpath(Dir); test.log("Directory created: " + result);
This function sets the environment variable called
name
to have the given
value
. The name
environment variable is created (and then set to the given
value
) if it doesn't already exist.
(See also, OS.getenv
.)
Example:
var preferredEditor = "vim"; OS.setenv("EDITOR", preferredEditor);
This function executes the given command
in a
shell (console). If the execution is successful the return status is
returned; otherwise -1 is returned to signify that an error occurred.
The command
string must hold the name of the
command to be executed, and may optionally include command line
arguments and shell redirection characters.
Here is an example that executes a custom application on Windows and
redirects its stdout
stream to a file:
var result = OS.system("C:\\testprograms\\readresult.exe > output.txt"); if (result == -1) test.fatal("readresult error occurred"); else if (result != 0) test.warning("readresult failed");
Here is another example: this sends an email on a Unix system:
var msg = "This is a mail from Squish"; OS.system("echo '" + msg + "' | mail -s Subject bugs@example.com");
See also the OS.capture
function.
The OS
object's read-only version
property
holds an array with information about the operating system that
squishrunner is running on. The array's elements are named "major",
"minor" and "name" and denote the version number and human-readable
representation.
Here is an example making use of this information to ensure test execution on supported operating systems:
var major = OS.version.major; if (major < 7) test.warning("Unsupported OS version " + OS.version.name);
The XML
object provides a parsing function that operates on
a string of XML-marked-up text, and that returns an XMLNode
object that provides methods which allow the XML to be traversed and
queried.
This function parses the given string of XML markup and returns a document node object that represents the root of the document tree. If the parse fails a catchable exception is thrown.
Note that the XML is assumed to use the UTF-8 encoding (which is the default for XML files that don't specify an encoding), even if an encoding is specified that isn't UTF-8.
XMLNode xmlNode.firstChildThis read-only node property holds this node's first child—or a null node if this node has no children.
This node method returns a string containing the value of the node's
attributeName
attribute. If the node doesn't have
an attribute called attributeName
, the method's
behavior is undefined. If the attributeName
is an
empty string, a catchable exception is thrown. All of a node's attribute
names can be retrieved using the xmlNode.getAttributeNames
function.
![]() | Element Nodes Only |
---|---|
This function must only be called on element nodes—those nodes
whose |
This node method returns a list of strings containing the names of all
the node's attributes. Any of these names can be used as the argument to
the xmlNode.getAttribute
function to get
the corresponding attribute's value.
![]() | Element Nodes Only |
---|---|
This function must only be called on element nodes—those nodes
whose |
This function returns true
if the node has an attribute
called attributeName
; otherwise
it returns false
.
![]() | Element Nodes Only |
---|---|
This function must only be called on element nodes—those nodes
whose |
This function returns a list of XMLNode
objects for the given
tagName
.
![]() | Document or Element Node Only |
---|---|
This function must only be called on document or element nodes—a node
whose |
This function evaluates a given XPath.Expression
on an XMLNode
object's parent
document and retrieves the first XMLNode
object the evaluation returns, or (if given XPath exptession doesn't
evaluate anything) null
will be beturned.
This function evaluates an XPath.Expression
on an XMLNode
object's parent document
and returns a list of XMLNode
objects.
This function evaluates a given XPath.Expression
on an XMLNode
object's parent
document and retrieves the content of the first XMLNode
object the evaluation returns. So return type
varies, depending on the type of content the returned XMLNode
object contains. If the evaluation won't
return any nodes, it will return null.
This function evaluates an XPath.Expression
on an XMLNode
object's parent document
and returns a JavaScript tuple, which elements are either: directly that contents which are contained in the returned
XMLNode
objects, or, if evaluation may return XMLNode
objects which contain just a subtree
of even more XMLNode
objects as children, these nodes then are contained in the tuple 'as are'.
This read-only node property is true
if the node is a null
node; otherwise it is false
.
This read-only node property holds this node's next sibling node (which will be a null node if this node has no next sibling).
String xmlNode.nodeNameThis node property holds the node's name, which is the tag name for element nodes. For the document node the node name is always “<anonymous xml document>”.
Integer xmlNode.nodeTypeThis node property holds the node's type as enum value. The possible type values are:
0 : XML.DocumentNode
1 : XML.ElementNode
2 : XML.CommentNode
3 : XML.UnknownType
4 : XML.TextNode
5 : XML.DeclarationNode
This node property holds the node's value. The meaning depends on the type of the node as follows:
XML.CommentNode
provides the comment text
XML.DeclarationNode
provides an empty text
XML.DocumentNode
provides the fixed text “<anonymous xml document>”
XML.TextNode
provides the text string
XML.UnknownType
provides the content of the tag
This node property holds the node's parent node or a null node if this node has no parent. (For example, the document node has no parent.)
String xmlNode.textContentThis node property holds the text contained within this node (which could be an empty string).
Note that this node property does not traverse its child nodes to produce a concatenation of all their texts. For example:
var documentNode = XML.parse("<a>Hello</a>"); var anchorNode = documentNode.firstChild; test.verify(anchorNode.textContent == "Hello"); documentNode = XML.parse("<a><b>Hello</b></a>"); anchorNode = documentNode.firstChild; test.verify(anchorNode.textContent == ""); var boldNode = anchorNode.firstChild; test.verify(boldNode.textContent == "Hello");
![]() | Element Nodes Only |
---|---|
This function must only be called on element nodes—those nodes
whose |
This function returns an XML-formatted string representation
of the XMLNode
object including tags, attributes and child
elements.
Squish provides its own APIs for accessing SQL databases since the JavaScript specification does not include them. To see the SQL APIs in action, see the JavaScript examples in How to Access Databases from Squish Test Scripts (Section 5.18).
The SQL
object provides a means of connecting to a
database, executing queries on the database, and traversing and
inspecting results. This functionality might be useful for retrieving
test data or for providing data to the AUT.
This function tries to connect to a SQL database. If it succeeds a SQLConnection Object (Section 6.16.8.2) is returned—this can be used to execute SQL statements on the database. If the connection fails a catchable exception is thrown. The information required to establish the connection must be passed as an object whose properties are then interpreted.
Here is an example invocation showing how to connect to a MySQL server on a host called “dulsberg”, with the given username and password:
var conn = SQL.connect( { Driver: "MySQL", Host: "dulsberg", Port: 1342, Database: "mydatabase", UserName: "test", Password: "secretPhrase" } );
The object's attributes have the following meanings:
The driver is used to specify what kind of database we are connecting to. Possible values are:
DB2* | IBM DB2, v7.1 and higher |
IBase* | Borland Interbase Driver |
MySQL | MySQL Driver |
ODBC | ODBC Driver (includes Microsoft® SQL Server) |
Oracle* | Oracle Call Interface Driver |
PostgreSQL | PostgreSQL v8.x Driver |
SQLite | SQLite 3 Driver |
Sybase* | Sybase Adaptive Server |
![]() | Commercial Database Drivers |
---|---|
The drivers marked with an asterisk (*) are not supported in Squish binary packages. This is usually because the database vendor's license does not permit redistributing their client libraries without owning a license for their product. The solution is to either try the ODBC driver, or to build Squish yourself against a Qt library which includes support for your particular SQL database. |
This is used to specify the host name (or the IP address) of the computer on which the SQL database is installed.
This is used to specify the port on the remote computer to which the connection should be established. If this is omitted, the default port for the specified driver is used.
This is used to specify the name of the database to which the connection should be made.
This is used to specify the Data Source Name (DSN) to use. Note that specifying this attribute is only necessary when using the ODBC driver.
This is used to specify the user name to use when logging into the database.
This is used to specify the password to use when logging into the database. If omitted, an empty password is assumed.
SQLConnection
objects are returned by the SQL.connect
function described above; the
object provides the methods listed below.
This method closes the SQL connection.
This method executes the given sql
statement
(such as DELETE
, INSERT
, or
UPDATE
) on the SQLConnection
object. If the
statement succeeds the number of rows affected is returned; or -1 if the
number cannot be determined. If an error occurs, a catchable exception
is thrown.
If the result returned by the statement needs to be read
(e.g. for CALL
) use
sqlConnection.query
.
This method executes the given sql
statement
(e.g., a SELECT
statement) on the
SQLConnection
object. If the statement succeeds a SQLResult Object (Section 6.16.8.3) is returned. If an error occurs, a
catchable exception is thrown.
Here is an example that shows how to execute a SQL query on a connection object:
var result = connection.query("SELECT last_name, first_name " + "FROM people WHERE country LIKE 'A%';");
SQLResult
objects are returned by the sqlConnection.execute
and sqlConnection.query
methods. A
SQLResult
object provides the functions and properties
listed below. Note that in the case of SELECT
statements,
the SQLResult
object is automatically set to the first row
(if any were retrieved).
This property is true
if the SQLResult
object
is in a valid state; otherwise it is false
. Some functions
return invalid result objects to indicate errors or other special
conditions (see below).
This property holds the number of rows affected by the query (for
example, the number of rows deleted, inserted, or updated)—or -1
if the number could not be determined. And for SELECT
queries this property holds the number of rows which this result
contains.
This function navigates to the first row in this result. This is
useful if you want to iterate over the rows multiple times: after
processing the rows using the sqlResult.toNext
function, call this function
to return to the first row so that you can use the sqlResult.toNext
function once again.
This function navigates to the next row in this SQL
result. If there is no next row (because there are no rows at all or
because we have already navigated to the last row), this
SQLResult
object is marked as invalid. This function
and the isValid
property make it easy to iterate over the
results of a SELECT
query. For example:
var result = connection.query("SELECT last_name, first_name " + "FROM people WHERE country LIKE 'A%';"); // result is automatically set the first row while (result.isValid) { // do something with the result result.toNext(); }
This function can be used to get the data in the given column (field) for the current row (record). The column can be identified by its position (counting from zero), or by using the (case-insensitive) field name. The data in the given column is implicitly converted into a string. Note that you can also use the bracket-syntax (shown in the example below) as a shortcut.
var result = connection.query("SELECT first_name, last_name " + "FROM people WHERE country LIKE 'A%';"); // result is automatically set the first row while (result.isValid) { var name1 = result.value(0) + " " + result.value(1); var name2 = result.value("first_name") + " " + result.value("last_name"); var name3 = result["first_name"] + " " + result["last_name"]; test.verify(name1 == name2 && name2 == name3); result.toNext(); }
This example shows three different ways of indexing fields, all of which are equivalent.
The Socket
object can be used as TCP client socket to connect to a server socket to read and write strings.
Example:
var socket = Socket.connect("192.168.1.42", 4711); socket.encoding = "latin1"; socket.writeString("hello"); var line = socket.readLine(); socket.close();
Here are some quick links to the Socket
object's properties and methods.
This method closes the socket connection. Once closed a socket object cannot be read from or written to.
This function tries to connect to the specified host name (or the IP address) and port and returns a socket object on success. If the connection failed a catchable exception is thrown.
String socket.encoding
The socket
object's encoding
property holds the encoding to read and write strings. The default encoding is "utf-8"
. Other possible values are "ucs-2"
(2 byte Unicode) and "latin1"
(also known as ISO 8859-1) which includes the US-ASCII range.
This property should be set before doing any reading or writing of strings.
String socket.localAddress
The socket
object's localAddress
property holds the address used on the local machine for the socket.
The socket
object's localPort
property holds the port used on the local machine for the socket.
This method reads a signed 8-bit integer from the socket. On success the integer value is returned otherwise a catchable exception is thrown.
This method reads a signed 32-bit integer from the socket. On success the integer value is returned otherwise a catchable exception is thrown.
This method reads until one of the line endings "\n"
or "\r\n"
are read from the socket returned by the Socket.connect
function. The content is assumed to be text using the UTF-8 encoding (unless the socket.encoding property is changed). On success the string is returned without line ending. If no line ending is received a catchable exception is thrown.
The socket
object's remoteAddress
property holds the address used on the remote machine for the socket.
The socket
object's remotePort
property holds the port used on the remote machine for the socket.
The socket
object's timeout
property holds the timeout used for read and write operations on the socket. It's an integer number of seconds which defaults to 20 seconds.
This property should be set before doing any reading or writing.
This method writes the given string
to the socket object returned by the Socket.connect
function. The string
is written using the UTF-8 encoding (unless the socket.encoding property is changed). If the writing fails a catchable exception is thrown.
The WebSocket
object implements text-based communication with a server via the WebSocket protocol. Its functions block until completion for convenient use within a test script.
var socket; try { socket = WebSocket.connect("websocket-server", 80); } catch (e) { test.log("Could not connect: " + e); return; } socket.timeout = 500; socket.sendTextMessage( "'Quack!' said the frog." ); test.log("received: " + socket.receiveTextMessage()); socket.close();
Connects to hostname:port
and returns a WebSocket object on success. On failure, an exception is thrown.
Closes a WebSocket connection.
Sends a text message through the WebSocket. Throws an exception on failure.
Receives a message from the WebSocket. Throws an exception if there is nothing to receive.
String websocket.hostA readonly property that holds the host this socket is connected to.
Boolean websocket.openA readonly property that tells if this socket is currently open.
Number websocket.portA readonly property that holds the port this socket is connected to.
Number websocket.timeoutHolds the timeout (default: 3000 ms) used when sending and receiving data through the WebSocket. This property can be changed at any time and expects a millisecond value.
The XMLHttpRequest
object can be used as a HTTP client
that can make GET
, HEAD
, POST
,
PUT
or DELETE
requests. Possible usage
ranges from querying the content of Web pages up to so called REST
calls with data transmitted as plain text, XML or JSON.
The constructor for the XMLHttpRequest
type.
This function will reset the client object and change the readyState
property back to UNSENT
.
This function returns the header field value from the response of which the field name matches header. A call like
var client = new XMLHttpRequest(); client.open("GET", "http://www.example.com/result.txt", false); client.send(); test.log(client.getResponseHeader("Content-Type"));
might log a result like "text/plain".
This function returns all headers from the response. Whereas each name/value pair is separated by a CR/LF sequence.
This function opens the client for a method
request to the
specified url
. The method
can be any of GET
, HEAD
, POST
,
PUT
or DELETE
.
The async
parameter has to
be false
.
The optional username
and password
parameters can be used for
authentication against the server.
Unlike in a Web browser the requests initiated through the
XMLHttpRequest object will run in the foreground only. Installation of
a handler receiving the data asynchronously is not
required. With async
set to false
calls to send() will wait for the response to fully have arrived before
returning.
This property holds the current state of the client. Possible values are
XMLHttpRequest.UNSENT
, OPENED
, HEADERS_RECEIVED
, LOADING
and DONE
. Given the synchronous send() mode the
intermediate states HEADERS_RECEIVED
and LOADING
will not be visible to the test
script.
In case of a successful request this property holds the server's response. The response text is expected to have been UTF-8 encoded. Here is an example that makes use of this property to check the content of a Web page:
var client = new XMLHttpRequest(); client.open('GET', 'https://www.froglogic.com', false); client.send(); test.compare(client.status, 200); test.verify(client.response.indexOf("Testing") >= 0);
This function initiates the request as specified by
XMLHttpRequest.open
. The data
argument is ignored if the request method is GET
or HEAD
. The optional boundary
is only
used when sending form data and sets the dividing boundary between key-value
pairs.
An fictional example demonstrating the addition of a customer to a database via a REST API call:
var client = new XMLHttpRequest(); client.open("POST", "http://www.example.com/rest/CUSTOMER/", false); client.send("<CUSTOMER><ID>60</ID><FIRSTNAME>Laura</FIRSTNAME><LASTNAME>Miller</LASTNAME><STREET>443 Seventh Av.</STREET><CITY>Lyon</CITY></CUSTOMER>"); test.compare(client.statusText, "Created");
Furthermore, this function can send FormData according to the FormData Web
API using an HTTP POST
or PUT
request. The following example shows how another customer can be
added to the same database as above using FormData.
var client = new XMLHttpRequest(); client.open("POST", "http://www.example.com/rest/CUSTOMER/", false); client.setRequestHeader( "Content-type", "multipart/form-data" ); var data = new FormData(); data.append("id", "61"); data.append("firstname", "John"); data.append("lastname", "Smith"); data.append("street", "1301 Ferguson Rd"); data.append("city", "Sebastopol"); client.send(data); test.compare(client.statusText, "Created");
When sending form data this way it is important to use
XMLHttpRequest.setRequestHeader
and to set the media type with
Content-type
to multipart/form-data
.
Setting the Content-type
header is imperative for data to be
interpreted correctly by the server.
It is possible to set a custom boundary used in the HTTP request body to separate the keys from the values and avoid any random boundaries. This boundary is provided as a second optional argument for the send method. The boundary should not exceed 70 characters and should contain only characters from the US-ASCII character set. When using UTF-8 characters please set the charset inside Content-Type header accordingly.
client.send(data, "CUSTOMBOUNDARY");
For further details how to handle such data please refer to the section FormData Object (Section 6.16.12).
This function adds a header to the list of request headers, of if
header
is already in the list of headers,
combines its value with
value
An example showing an explicit setting of
the type of message being sent:
client.setRequestHeader("Content-Type", "text/plain;charset=UTF-8"); client.send(message);Number XMLHttpRequest.status
This read-only property holds the HTTP status code of the previous request. For example, 200 if a GET request succeeded. See the Status Code Registry for a complete listing.
String XMLHttpRequest.statusTextThis read-only property holds the HTTP status text of the previous request. For example, "OK" if a GET request succeeded. See the Status Code Registry for a complete listing.
The FormData
object offers a key-value-based container for
handling data collected in forms. It resembles the FormData Web
API. Most of the functions have been implemented to enable test
suites to prepare, handle and send FormData using
XMLHttpRequest.send
of the XMLHttpRequest Object (Section 6.16.11).
The following example shows the creation of a FormData object and usage of all its methods. Accompanying descriptions follow further below.
var data = new FormData(); // appending values data.append("key", "value 1"); data.append("key", "value 2"); var valueList = data.getAll("key"); // looking for values if (data.has("key")) { // ... } // overwriting values data.set("key", "new value"); var singleValue = data.get("key"); // removing values data.remove("key");
This method appends a value
of any type identified by a
key
. The FormData container can store multiple values for
one key. All values are handled as strings. Additional parsing is needed for
handling other types.
It is also possible to append files. In contrast to the Web API for FormData documentation, Squish utilizes the File API offered by File Object (Section 6.16.4). The following example appends a plain text file to a FormData instance.
![]() | Caution |
---|---|
Sending binary files is currently not supported. |
var data = new FormData(); var file = File.open("data.txt","r"); data.append("test.txt", file.read()); file.close();
For more details about the File object and its methods, see
File.open
,
file.read
and
file.close
.
Gets a single value stored with data.append
or data.set
. It returns either a single
value or the first stored value for keys with multiple values.
Returns all values for a given key as a list.
Returns true
if the container has a value for key
,
otherwise false
.
Removes all values for key
. If multiple values were stored
all of them are removed.
Overrides the stored key
-value
pair
with the provided value. If there were multiple values before, all of them will
be removed before adding the new value.