Home > Articles > Open Source > Ajax & JavaScript

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

3.4 One Test Runner to Rule Them All

The problem with in-browser testing frameworks is that they can be cumbersome to work with, especially in a test-driven development setting where we need to run tests continuously and integrated into the workflow. Additionally, testing on a wide array of platform/browser combinations can entail quite a bit of manual work. Headless frameworks are easier to work with, but fail at testing in the actual environment the code will be running in, reducing their usefulness as testing tools. A fairly new player on the field of xUnit testing frameworks is JsTestDriver, originating from Google. In contrast to the traditional frameworks, JsTestDriver is first and foremost a test runner, and a clever one at that. JsTestDriver solves the aforementioned problems by making it easy both to run tests and to test widely in real browsers.

3.4.1 How JsTestDriver Works

JsTestDriver uses a small server to run tests. Browsers are captured by the test runner and tests are scheduled by issuing a request to the server. As each browser runs the tests, results are sent back to the client and presented to the developer. This means that as browsers are idly awaiting tests, we can schedule runs from either the command line, the IDE, or wherever we may feel most comfortable running them from. This approach has numerous advantages:

  • Tests can be run in browsers without requiring manual interaction with the browser.
  • Tests can be run in browsers on multiple machines, including mobile devices, allowing for arbitrary complex testing grids.
  • Tests run fast, due to the fact that results need not be added to the DOM and rendered, they can be run in any number of browsers simultaneously, and the browser doesn't need to reload scripts that haven't changed since the tests were last run.
  • Tests can use the full DOM because no portion of the document is reserved for the test runner to display results.
  • No need for an HTML fixture, simply provide one or more scripts and test scripts, an empty document is created on the fly by the test runner.

JsTestDriver tests are fast. The test runner can run complex test suites of several hundred tests in under a single second. Because tests are run simultaneously, tests will still run in about a second even when testing 15 browsers at the same time. Granted, some time is spent communicating with the server and optionally refreshing the browser cache, but a full run still completes in a matter of a few seconds. Single test case runs usually complete in the blink of an eye.

As if faster tests, simpler setup, and full DOM flexibility weren't enough, JsTest-Driver also offers a plugin that calculates test coverage, XML test report output compatible with JUnit's reports, meaning we can immediately use existing continuous integration servers, and it can use alternative assertion frameworks. Through plug-ins, any other JavaScript testing framework can take advantage of the JsTestDriver test runner, and at the time of writing, adapters for QUnit and YUI Test already exist. This means tests can be written using YUI Test's assertions and syntax, but run using JsTestDriver.

3.4.2 JsTestDriver Disadvantages

At the time of writing, JsTestDriver does not support any form of asynchronous testing. As we will see in Chapter 12, Abstracting Browser Differences: Ajax, this isn't necessarily a problem from a unit testing perspective, but it may limit the options for integration tests, in which we want to fake as little as possible. It is possible that asynchronous test support will be added to future versions of JsTestDriver.

Another disadvantage of JsTestDriver is that the JavaScript required to run tests is slightly more advanced, and may cause a problem in old browsers. For instance, by design, a browser that is to run JsTestDriver needs to support the XMLHttpRequest object or similar (i.e., Internet Explorer's corresponding ActiveX object) in order to communicate with the server. This means that browsers that don't support this object (older browsers, Internet Explorer before version 7 with ActiveX disabled) cannot be tested with the JsTestDriver test runner. This problem can be effectively circumvented, however, by using YUI Test to write tests, leaving the option of running them manually with the default test runner in any uncooperative browser.

3.4.3 Setup

Installing and setting up JsTestDriver is slightly more involved than the average in-browser testing framework; still, it will only take a few minutes. Also, the setup is only required once. Any projects started after the fact are dirt simple to get running. JsTestDriver requires Java to run both the server component and start test runs. I won't give instructions on installing Java here, but most systems have Java installed already. You can check if Java is installed by opening a shell and issue the java-version command. If you don't have Java installed, you will find instructions on java.com. Download the Jar File

Once Java is set up, download the most recent JsTestDriver jar file from http://code.google.com/p/js-test-driver/downloads/list. All the examples in this book use version 1.2.1, be sure to use that version when following along with the examples. The jar file can be placed anywhere on the system, I suggest ~/bin. To make it easier to run, set up an environment variable to point to this directory, as shown in Listing 3.3.

Listing 3.3. Setting the $JSTESTDRIVER_HOME environment variable


Set the environment variable in a login script, such as .bashrc or .zshrc (depends on the shell—most systems use Bash, i.e., ~/.bashrc, by default). Windows Users

Windows users can set an environment variable in the cmd command line by issuing the set JSTESTDRIVER_HOME=C:\bin command. To set it permanently, right-click My Computer (Computer in Windows 7) and select Properties. In the System window, select Advanced system properties, then the Advanced tab, and then click the Environment Variables ... button. Decide if you need to set the environment variable for yourself only or for all users. Click New, enter the name (JSTEST-DRIVER_HOME) in the top box, and then the path where you saved the jar file in the bottom one. Start the Server

To run tests through JsTestDriver, we need a running server to capture browsers with. The server can run anywhere reachable from your machine—locally, on a machine on the local network, or a public facing machine. Beware that running the server on a public machine will make it available to anyone unless the machine restricts access by IP address or similar. To get started, I recommend running the service locally; this way you can test while being offline as well. Open a shell and issue the command in either Listing 3.4 or Listing 3.5 (current directory is not important for this command).

Listing 3.4. Starting the JsTestDriver server on Linux and OSX

java -jar $JSTESTDRIVER_HOME/JsTestDriver-1.2.1.jar --port

Listing 3.5. Starting the JsTestDriver server on Windows

java -jar %JSTESTDRIVER_HOME%\JsTestDriver-1.2.1.jar --port

Port 4224 is the defacto standard JsTestDriver port, but it is arbitrarily picked and you can run it on any port you want. Once the server is running, the shell running it must stay open for as long as you need it. Capturing Browsers

Open any browser and point it to http://localhost:4224 (make sure you change the port number if you used another port when starting the server). The resulting page will display two links: Capture browser and Capture in strict mode. JsTestDriver runs tests inside an HTML 4.01 document, and the two links allow us to decide if we want to run tests with a transitional or strict doctype. Click the appropriate link, and leave the browser open. Repeat in as many browsers as desired. You can even try hooking up your phone or browsers on other platforms using virtual instances. Running Tests

Tests can be run from the command line, providing feedback in much the same way a unit testing framework for any server-side language would. As tests are run, a dot will appear for every passing test, an F for a failing test, and an E for a test with errors. An error is any test error that is not a failing assertion, i.e., an unexpected exception. To run the tests, we need a small configuration file that tells JsTestDriver which source and test files to load (and in what order), and which server to run tests against. The configuration file, jsTestDriver.conf by default, uses YAML syntax, and at its simplest, it loads every source file and every test file, and runs tests at http://localhost:4224, as seen in Listing 3.6.

Listing 3.6. A barebone jsTestDriver.conf file

server: http://localhost:4224

  - src/*.js
  - test/*.js

Load paths are relative to the location of the configuration file. When it's required to load certain files before others, we can specify them first and still use the *.js notation, JsTestDriver will only load each file once, even when it is referenced more than once. Listing 3.7 shows an example where src/mylib.js always need to load first.

Listing 3.7. Making sure certain files load first

server: http://localhost:4224

  - src/mylib.js
  - src/*.js
  - test/*.js

In order to test the configuration we need a sample project. We will revisit the strftime example once again, so start by copying the strftime.js file into the src directory. Then add the test case from Listing 3.8 in test/strftime_test.js.

Listing 3.8. Date.prototype.strftime test with JsTestDriver

TestCase("strftimeTest", {
  setUp: function () {
    this.date = new Date(2009, 9, 2, 22, 14, 45);

  tearDown: function () {
    delete this.date;

  "test %Y should return full year": function () {
    var year = Date.formats.Y(this.date);

    assertEquals(2009, year);

  "test %m should return month": function () {
    var month = Date.formats.m(this.date);

    assertEquals("10", month);

  "test %d should return date": function () {
    assertEquals("02", Date.formats.d(this.date));

  "test %y should return year as two digits": function () {
    assertEquals("09", Date.formats.y(this.date));

  "test %F should act as %Y-%m-%d": function () {
    assertEquals("2009-10-02", this.date.strftime("%F"));

The test methods are almost syntactically identical to the YUI Test example, but note how this test case has less scaffolding code to support the test runner. Now create the configuration file as shown in Listing 3.9.

Listing 3.9. JsTestDriver configuration

server: http://localhost:4224

  - src/*.js
  - test/*.js

We can now schedule tests to run by issuing the command in Listing 3.10 or Listing 3.11, depending on your operating system.

Listing 3.10. Running tests with JsTestDriver on Linux and OSX

java -jar $JSTESTDRIVER_HOME/JsTestDriver-1.2.1.jar --tests

Listing 3.11. Running tests with JsTestDriver on Windows

java -jar %JSTESTDRIVER_HOME%\JsTestDriver-1.2.1.jar--tests

The default configuration file name is jsTestDriver.conf, and as long as this is used we don't need to specify it. When using another name, add the --config path/to/file.conf option.

When running tests, JsTestDriver forces the browser to refresh the test files. Source files, however, aren't reloaded between test runs, which may cause errors due to stale files. We can tell JsTestDriver to reload everything by adding the --reset option. JsTestDriver and TDD

When TDD-ing, tests will fail frequently, and it is vital that we are able to quickly verify that we get the failures we expect in order to avoid buggy tests. A browser such as Internet Explorer is not suitable for this process for a few reasons. First, its error messages are less than helpful; you have probably seen "Object does not support this property or method" more times than you care for. The second reason is that IE, at least in older versions, handles script errors badly. Running a TDD session in IE will cause it to frequently choke, requiring you to manually refresh it. Not to mention the lack of performance in IE, which is quite noticeable compared to, e.g., Google Chrome.

Disregarding Internet Explorer, I would still advise against keeping too many browsers in your primary TDD process, because doing so clutters up the test runner's report, repeating errors and log messages once for every captured browser. My advice is to develop against one server that only captures your browser of choice, and frequently run tests against a second server that captures many browsers. You can run against this second server as often as needed—after each passed test, completed method, or if you are feeling bold, even more. Keep in mind that the more code you add between each run, the harder it will be to spot any bugs that creep up in those secondary browsers.

To ease this sort of development, it's best to remove the server line from the configuration file and use the --server command line option. Personally I do this kind of development against Firefox, which is reasonably fast, has good error messages, and always runs on my computer anyway. As soon as I pass a test, I issue a run on a remote server that captures a wider variety of browsers, new and old.

3.4.4 Using JsTestDriver From an IDE

JsTestDriver also ships plugins for popular integrated development environments (IDEs), Eclipse and IntelliJ IDEA. In this section I will walk through setting up the Eclipse plugin and using it to support a test-driven development process. If you are not interested in developing in Eclipse (or Aptana), feel free to skip to Section 3.4.5, Improved Command Line Productivity. Installing JsTestDriver in Eclipse

To get started you need to have Eclipse (or Aptana Studio, an IDE based on Eclipse aimed at web developers) installed. Eclipse is a free open source IDE and can be downloaded from http://eclipse.org. Once Eclipse is running, go to the Help menu and select Install new software. In the window that opens, enter the following URL as a new update site: http://js-test-driver.googlecode.com/svn/update/

"JS Test Driver Eclipse Plugin" should now be displayed with a checkbox next to it. Check it and click Next. The next screen is a confirmation that sums up the plugins to be installed. Click Next once again and Eclipse asks you to accept the terms of use. Check the appropriate radio button and click Next if you accept. This should finish the installation.

Once the plugin is installed we need to configure it. Find the Preferences pane under the Window menu (Eclipse menu on OS X). There should be a new entry for Js Test Driver; select it. As a bare minimum we need to enter the port where Eclipse should run the server. Use 4224 to follow along with the example. You can also enter the paths to browsers installed locally to ease browser capturing, but it's not really necessary. Running JsTestDriver in Eclipse

Next up, we need a project. Create a new project and enter the directory for the command line example as location. Now start the server. Locate the JsTestDriver panel in Eclipse and click the green play button. Once the server is running, click the browser icons to capture browsers (given that their path was configured during setup). Now right-click a file in the project, and select Run As and then Run Configurations... Select Js Test Driver Test and click the sheet of paper icon indicating "new configuration." Give the configuration a name and select the project's configuration file. Now click run and the tests run right inside Eclipse, as seen in Figure 3.2.

Figure 3.2

Figure 3.2 Running JsTestDriver tests inside Eclipse.

On subsequent runs, simply select Run As and then Name of configuration. Even better, check the Run on every save checkbox in the configuration prompt. This way, tests are run anytime a file in the project is saved, perfect for the test-driven development process.

3.4.5 Improved Command Line Productivity

If the command line is your environment of choice, the Java command to run tests quickly becomes a bit tiresome to type out. Also, it would be nice to be able to have tests run automatically whenever files in the project change, just like the Eclipse and IDEA plugins do. Jstdutil is a Ruby project that adds a thin command line interface to JsTestDriver. It provides a leaner command to run tests as well as an jsautotest command that runs related tests whenever files in the project change.

Jstdutil requires Ruby, which comes pre-installed on Mac OS X. For other systems, installation instructions can be found on ruby-lang.org. With Ruby installed, install Jstdutil by running `gem install jstdutil` in a shell. Jstdutil uses the previously mentioned $JSTESTDRIVER_HOME environment variable to locate the JsTestDriver jar file. This means that running tests is a simple matter of `jstestdriver --tests all`, or for autotest, simply `jsautotest`. If the configuration file is not automatically picked up, specify it using `jstestdriver --config path/to/file.conf --tests all`. The jstestdriver and jsautotest commands also add coloring to the test report, giving us that nice red/green visual feedback.

3.4.6 Assertions

JsTestDriver supports a rich set of assertions. These assertions allow for highly expressive tests and detailed feedback on failures, even when a custom assertion message isn't specified. The full list of supported assertions in JsTestDriver is:

  • assert(msg, value)
  • assertTrue(msg, value)
  • assertFalse(msg, value)
  • assertEquals(msg, expected, actual)
  • assertNotEquals(msg, expected, actual)
  • assertSame(msg, expected, actual)
  • assertNotSame(msg, expected, actual)
  • assertNull(msg, value)
  • assertNotNull(msg, value)
  • assertUndefined(msg, value)
  • assertNotUndefined(msg, value)
  • assertNaN(msg, number)
  • assertNotNaN(msg, number)
  • assertException(msg, callback, type)
  • assertNoException(msg, callback)
  • assertArray(msg, arrayLike)
  • assertTypeOf(msg, type, object)
  • assertBoolean(msg, value)
  • assertFunction(msg, value)
  • assertNumber(msg, value)
  • assertObject(msg, value)
  • assertString(msg, value)
  • assertMatch(msg, pattern, string)
  • assertNoMatch(msg, pattern, string)
  • assertTagName(msg, tagName, element)
  • assertClassName(msg, className, element)
  • assertElementId(msg, id, element)
  • assertInstanceOf(msg, constructor, object)
  • assertNotInstanceOf(msg, constructor, object)

We will be using JsTestDriver for most examples throughout this book.

  • + Share This
  • 🔖 Save To Your Account

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.


Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.


If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.


This site is not directed to children under the age of 13.


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020