添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
相关文章推荐
神勇威武的山羊  ·  三、typescript 断言 | ...·  8 小时前    · 
路过的毛衣  ·  TypeScript 的元组类型 - ...·  8 小时前    · 
幸福的番茄  ·  ?java ...·  10 小时前    · 
任性的青蛙  ·  ADT Explorer - ...·  6 天前    · 
爱旅游的手套  ·  Logrotate - Gentoo wiki·  3 周前    · 
逼格高的凉面  ·  Maven Central: ...·  5 月前    · 
发怒的小蝌蚪  ·  C# WPF Treeview ...·  1 年前    · 

Squish assumes that all test.js files use the UTF-8 encoding. If you expect to edit such files outside of the squishide , make sure that the editor loads and saves the files using UTF-8.

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:

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

    Language Core

    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 .

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

    Squish ECMAScript Support

    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 .

    Keywords

    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

    Punctuators

    {}, \c {} , ( , ) , [ , ] , . , , , ; < , > , <= , >= , == , != , === , !== , + , - , * , / , % , ** , ++ , -- , << , >> , >>> , & , | , ^ , ! , ~ , && , || , ?? , ... ? , : , = , += , -= , *= , /= , %= , **= , <<= , >>= , >>>= , &= , |= , ^= , &&= , ||= , ??= and => .

    The Global Object

    Value Properties

  • Infinity
  • undefined
  • Function Properties

  • decodeURI()
  • decodeURIComponent()
  • encodeURI()
  • encodeURIComponent()
  • escape()
  • eval()
  • isFinite()
  • parseFloat()
  • parseInt()
  • unescape()
  • Constructor Properties

  • Array
  • Boolean
  • Error
  • Function
  • Number
  • Object
  • RegExp
  • String
  • EvalError
  • RangeError
  • ReferenceError
  • SyntaxError
  • TypeError
  • URIError
  • Other Properties

    Array

    Prototype Function Properties

  • concat()
  • every()
  • filter()
  • forEach()
  • indexOf()
  • join()
  • lastIndexOf()
  • map()
  • pop()
  • push()
  • reduce()
  • reduceRight()
  • reverse()
  • shift()
  • slice()
  • some()
  • sort()
  • splice()
  • toLocaleString()
  • toString()
  • unshift()
  • Boolean

    Prototype Function Properties

  • toString()
  • valueOf()
  • Prototype Function Properties

  • 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()
  • Error

    Prototype Value Properties

  • message
  • Function Properties

  • toString()
  • Function

    Prototype Value Properties

  • length
  • Prototype Function Properties

  • apply()
  • bind()
  • call()
  • toString()
  • The JSON Object

    Function Properties

  • parse()
  • stringify()
  • Prototype Function Properties

  • clear()
  • delete()
  • forEach()
  • get()
  • has()
  • keys()
  • set()
  • values()
  • The Math Object

    Value Properties

  • LOG10E
  • LOG2E
  • SQRT1_2
  • SQRT2
  • Function Properties

  • abs()
  • acos()
  • asin()
  • atan()
  • atan2()
  • ceil()
  • cos()
  • exp()
  • floor()
  • log()
  • max()
  • min()
  • pow()
  • random()
  • round()
  • sin()
  • sqrt()
  • tan()
  • Number

    Prototype Function Properties

  • toExponential()
  • toFixed()
  • toLocaleString()
  • toPrecision()
  • toString()
  • valueOf()
  • Object

    Function Properties

  • create()
  • defineProperties()
  • defineProperty()
  • freeze()
  • getOwnPropertyDescriptor()
  • getOwnPropertyNames()
  • getPrototypeOf()
  • isExtensible()
  • isFrozen()
  • isSealed()
  • keys()
  • preventExtensions()
  • seal()
  • setPrototypeOf()
  • Prototype Function Properties

  • eval()
  • hasOwnProperty()
  • isPrototypeOf()
  • propertyIsEnumerable()
  • toLocaleString()
  • toString()
  • valueOf()
  • __defineGetter__()
  • __defineSetter__()
  • RegExp

    Value Properties

  • $1...$9
  • Prototype Value Properties

  • global
  • ignoreCase
  • lastIndex
  • multiline
  • source
  • Prototype Function Properties

  • add()
  • clear()
  • delete()
  • entries()
  • forEach()
  • has()
  • keys()
  • values()
  • String

    Constructor Function Properties

  • fromCharCodeAt()
  • Prototype Function Properties

  • 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()
  • 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:

    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()
  • File.copy(source, target)
  • file.encoding
  • Boolean File.exists(fileOrDirectory)
  • File File.open(fileName)
  • StringList File.glob(pattern, [pattern...])
  • String file.read()
  • String file.readln()
  • Boolean File.remove(fileName)
  • File.separator
  • Number File.size(fileName)
  • file.write(string)
  • 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, Boolean File.remove(fileName) 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, 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.

    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(string) method can be called, and for files opened in read mode the String file.read() and String 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 File.open(fileName) 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 File.open(fileName) 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 File.open(fileName) 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).

    console Object

    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:

  • console.assert(bool, string [optional])
  • 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:

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

    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:

  • OS.argv
  • String OS.capture(command)
  • OS.chdir(path)
  • String OS.cwd()
  • String OS.getenv(name)
  • Array OS.listDir(path)
  • OS.machine
  • OS.name
  • OS.pause(msecs)
  • Boolean OS.removeRecursively(path)
  • Boolean OS.rmdir(path)
  • Boolean OS.mkpath(path)
  • OS.setenv(name, value)
  • int OS.system(command)
  • OS.version
  • 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 ).

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

    String OS.capture(command)

    This function executes the given command in a shell (console) just like the int OS.system(command) 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 int OS.system(command) 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 Array OS.listDir(path) 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:

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

    String OS.cwd()

    This function returns the current working directory as a string.

    Example:

    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(name, value).)

    Example:

    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:

    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", "arm64" 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(seconds) 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:

    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:

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

    Boolean OS.mkpath(path)

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

    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, String OS.getenv(name).)

    Example:

    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:

    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 [email protected]");

    See also the String OS.capture(command) 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:

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

    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 ListOfString xmlNode.getAttributeNames() function.

    Note: 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 String xmlNode.getAttribute(attributeName) function to get the corresponding attribute's value.

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

    ListOfXMLNode xmlNode.getElementsByTagName(tagName)

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

    Note: 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 other nodes will cause a catchable exception to be thrown.

    XMLNode XMLNode.selectSingleNode(XPathExpression)

    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.

    jsTupelOfValues xmlNode.selectNodes(XPath.Expression)

    This function evaluates an XPath.Expression on an XMLNode object's parent document and returns a list of XMLNode objects.

    jsValue XMLNode.getSingleValueByXPath(XPathExpression)

    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.

    jsTupelOfValues XMLNode.getValuesByXPath(XPath.Expression)

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

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

    Integer xmlNode.nodeType

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

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

    String xmlNode.toXMLString()

    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.

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

  • Driver: The driver is used to specify what kind of database we are connecting to. Possible values are:
  •