6.16. JavaScript Notes and Extension APIs

Table of Contents

6.16.1. JavaScript Language Documentation
6.16.2. Language Core
6.16.3. File Object
6.16.4. Console Object
6.16.5. OS Object
6.16.6. XML Object
6.16.7. SQL
6.16.8. Socket Object
6.16.9. WebSocket Object
6.16.10. XMLHttpRequest Object

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.

6.16.1. JavaScript Language Documentation

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:

If you prefer books, a good JavaScript book is JavaScript: The Definitive Guide by David Flanagan.

6.16.2. Language Core

The JavaScript engine shipped with Squish is compliant with the ECMAScript language specification (ECMA 262 Edition 3, parts of Edition 4 and 5). The language core that is defined in this standard encompasses operators, control structures, objects, and other features commonly found in a scripting language. A set of built-in classes provide methods for the most common data handling—these classes are: Boolean, Date, Error, Function, Map, Number, Object, RegExp, String, and JSON.

[Note]Invoking Java Functions from JavaScript

Some Java™ functions or methods have the same names as JavaScript reserved words. It is still possible to call such functions or methods, but to avoid conflicts with reserved words we must use a slightly different syntax. For example, to call object obj's delete method (which conflicts with JavaScript's delete reserved word), instead of writing obj.delete() we must write obj["delete"]() instead.

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.

[Note]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 C:\My Documents\test-plan.odt or /home/user/test-plan.odt. In most scripting languages, including JavaScript, the backslash character (\) is used to start an escape sequence inside strings and so cannot be written by itself. For this reason, when writing Windows paths in JavaScript strings we must escape the backslash—for example, "C:\\My Documents\\test-plan.odt".

6.16.3. File Object

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:

JavaScript
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.

file.close();

This method closes the file object it is called on. Once closed a file object cannot be read from or written to.

File.copy(source, target);

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.

String file.encoding

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) 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.

Boolean File.exists(fileOrDirectory);

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);

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.

StringList File.glob(pattern, [pattern...]);

This function returns the list of paths matching any of the given patterns.

String file.read();

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).

String file.readln();

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.

Boolean File.remove(fileName);

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.

String File.separator

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, "/".

Number File.size(fileName);

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).

file.write(string);

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).

6.16.4. Console Object

The Console object provides functions for basic interaction with script execution. The Console object is not a standard Java Script object, but is well known from web browsers.

Here are some quick links to the Console Object's methods:

Console.assert(bool, string [optional]);

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:

JavaScript
var index = findIndexOfSomething( "something" );
Console.assert( index >= 0, "Something not found, execution aborted!" );
someting[ index ].doSomething();

6.16.5. OS Object

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:

Array OS.argv

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:

JavaScript
var filename = "defaultfile.txt";
if (OS.argv.length > 1) {
    filename = OS.argv[1];
}

String OS.capture(command);

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:

JavaScript
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.

OS.chdir(path);

This function changes the test script's current working directory to the specified path.

Example:

JavaScript
var path = OS.cwd() + "/results";
OS.chdir(path);

String OS.cwd();

This function returns the current working directory as a string.

Example:

JavaScript
var path = OS.cwd();
test.log("Current working directory: " + path);

String OS.getenv(name);

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:

JavaScript
var homeDir = OS.getenv("HOME");
test.log("Current user's home directory: " + homeDir);

Array OS.listDir(path);

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:

JavaScript
var files = OS.listDir("C:\\temp\\output");
for (var i in files)
    test.log("Found generated file: " + files[i]);
String OS.machine

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" or "ia64". On Unix-like systems the value is the same as the output of uname -m, e.g. "i686", "x86_64", etc.

String OS.name

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.

OS.pause(msecs);

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.

Boolean OS.removeRecursively(path);

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:

JavaScript
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);

Boolean OS.rmdir(path);

This function deletes the directory found at path. It must be empty at the time of deletion. On success, the function returns true.

Example:

JavaScript
var oldDir = "C:\\build_old";
var result = OS.rmdir(oldDir);
test.log("Deletion result: " + result);

OS.setenv(name, value);

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:

JavaScript
var preferredEditor = "vim";
OS.setenv("EDITOR", preferredEditor);

int OS.system(command);

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:

JavaScript
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:

JavaScript
var msg = "This is a mail from Squish";
OS.system("echo '" + msg + "' | mail -s Subject bugs@example.com");

See also the OS.capture function.

Array OS.version

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:

JavaScript
var major = OS.version.major;
if (major < 7)
    test.warning("Unsupported OS version " + OS.version.name);

6.16.6. XML Object

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.

XMLNode XML.parse(markup);

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.firstChild

This read-only node property holds this node's first child—or a null node if this node has no children.

String xmlNode.getAttribute(attributeName);

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.

[Note]Element Nodes Only

This function must only be called on element nodes—those nodes whose nodeType attribute's value is XML.ElementNode. Calling the function on non-element nodes will cause a catchable exception to be thrown.

ListOfString xmlNode.getAttributeNames();

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.

[Note]Element Nodes Only

This function must only be called on element nodes—those nodes whose nodeType attribute's value is XML.ElementNode. Calling the function on non-element nodes will cause a catchable exception to be thrown.

Boolean xmlNode.hasAttribute(attributeName);

This function returns true if the node has an attribute called attributeName; otherwise it returns false.

[Note]Element Nodes Only

This function must only be called on element nodes—those nodes whose nodeType property's value is XML.ElementNode. Calling the function on non-element nodes will cause a catchable exception to be thrown.

ListOfXMLNode xmlNode.getElementsByTagName(tagName);

This function returns a list of XMLNode objects for the given tagName.

[Note]Document or Element Node Only

This function must only be called on document or element nodes—a node whose nodeType property's value is XML.DocumentNode or XML.ElementNode respectively. Calling the function on a non-element node will cause a catchable exception to be thrown.

Boolean xmlNode.isNull

This read-only node property is true if the node is a null node; otherwise it is false.

XMLNode xmlNode.nextSibling

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.nodeName

This 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>”.

String xmlNode.nodeType

This node property holds the node's type name. The possible type names are:

  • XML.CommentNode

  • XML.DeclarationNode

  • XML.DocumentNode

  • XML.ElementNode

  • XML.TextNode

  • XML.UnknownType

String xmlNode.nodeValue

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

XMLNode xmlNode.parentNode

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.textContent

This 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:

JavaScript
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");
[Note]Element Nodes Only

This function must only be called on element nodes—those nodes whose nodeType property's value is XML.ElementNode. Calling the function on non-element nodes will cause a catchable exception to be thrown.

String xmlNode.toXMLString();

This function returns an XML-formatted string representation of the XMLNode object including tags, attributes and child elements.

6.16.7. SQL

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).

6.16.7.1. SQL Object

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.

SQLConnection SQL.connect(informationObject);

This function tries to connect to a SQL database. If it succeeds a SQLConnection Object (Section 6.16.7.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:

JavaScript
var conn = SQL.connect( { Driver: "MySQL",
                          Host: "dulsberg",
                          Port: 1342,
                          Database: "mydatabase",
                          UserName: "test",
                          Password: "secretPhrase" } );

The object's attributes have the following meanings:

Driver

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
MySQLMySQL Driver
ODBCODBC Driver (includes Microsoft® SQL Server)
Oracle*Oracle Call Interface Driver
PostgreSQLPostgreSQL v8.x Driver
SQLiteSQLite 3 Driver
Sybase*Sybase Adaptive Server
[Note]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.

Host

This is used to specify the host name (or the IP address) of the computer on which the SQL database is installed.

Port

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.

Database

This is used to specify the name of the database to which the connection should be made.

DataSource

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.

UserName

This is used to specify the user name to use when logging into the database.

Password

This is used to specify the password to use when logging into the database. If omitted, an empty password is assumed.

6.16.7.2. SQLConnection Object

SQLConnection objects are returned by the SQL.connect function described above; the object provides the methods listed below.

sqlConnection.close();

This method closes the SQL connection.

Number sqlConnection.execute(sql);

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.

SQLResult sqlConnection.query(sql);

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.7.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:

JavaScript
var result = connection.query("SELECT last_name, first_name " +
        "FROM people WHERE country LIKE 'A%';");

6.16.7.3. SQLResult Object

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).

Boolean sqlResult.isValid

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).

int sqlResult.size

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.

sqlResult.toFirst();

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.

sqlResult.toNext();

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:

JavaScript
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();
}

String sqlResult.value(fieldNumber|fieldName);

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.

JavaScript
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.

6.16.8. Socket Object

The Socket object can be used as TCP client socket to connect to a server socket to read and write strings.

Example:

JavaScript
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.

socket.close();

This method closes the socket connection. Once closed a socket object cannot be read from or written to.

socket Socket.connect(host, port);

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.

Number socket.localPort

The socket object's localPort property holds the port used on the local machine for the socket.

Number socket.readInt8();

This method reads a signed 8-bit integer from the socket. On success the integer value is returned otherwise a catchable exception is thrown.

Number socket.readInt32();

This method reads a signed 32-bit integer from the socket. On success the integer value is returned otherwise a catchable exception is thrown.

String socket.readLine();

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.

String socket.remoteAddress

The socket object's remoteAddress property holds the address used on the remote machine for the socket.

Number socket.remotePort

The socket object's remotePort property holds the port used on the remote machine for the socket.

Number socket.timeout

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.

Socket.writeString(string);

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.

6.16.9. WebSocket Object

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();

WebSocket WebSocket.connect( hostname port );

Connects to hostname:port and returns a WebSocket object on success. On failure, an exception is thrown.

websocket.close();

Closes a WebSocket connection.

websocket.sendTextMessage( message );

Sends a text message through the WebSocket. Throws an exception on failure.

String websocket.receiveTextMessage();

Receives a message from the WebSocket. Throws an exception if there is nothing to receive.

String websocket.host

A readonly property that holds the host this socket is connected to.

Boolean websocket.open

A readonly property that tells if this socket is currently open.

Number websocket.port

A readonly property that holds the port this socket is connected to.

Number websocket.timeout

Holds 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.

6.16.10. XMLHttpRequest Object

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.

client.abort();

This function will reset the client object and change the readyState property back to UNSENT.

String client.getResponseHeader(header);

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".

String client.getAllResponseHeaders();

This function returns all headers from the response. Whereas each name/value pair is separated by a CR/LF sequence.

client.open(method, url, async, [username], [password]);

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.

Number client.readyState

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.

String client.responseText

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:

JavaScript
var client = new XMLHttpRequest();
client.open('GET', 'http://www.froglogic.com', false);
client.send();
test.compare(client.status, 200);
test.verify(client.response.indexOf("Testing") >= 0);

client.send([data]);

This function initiates the request as specified by client.open. The data argument is ignored if the request method is GET or HEAD. An fictional example demonstrating the addition of a customer to a database via a REST API call:

JavaScript
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");

client.setRequestHeader(header, value);

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 client.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 client.statusText

This 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.