YUI Test - The New Kid on Block

One of the great features of the Ektron content management system platform is that it plays well with other technologies. At VanDamme Associates, we often mix custom JavaScript and AJAX elements into our Ektron solutions.

Ektron itself is no stranger to AJAX, and it even bundles a tweaked version of JQuery in the standard distribution. One good tool for testing JavaScript, that Ektron has blogged about, is the venerable JsUnit framework. While JsUnit is a solid tool, there are drawbacks.

  • Although JsUnit has been available since 2001, it’s still the love child of a sole developer.
    JsUnit’s release schedule is irregular. (Release 2.2 has been in “beta” for over two years now.)

Look Ahead

Happily, there’s a new kid on the block: YUI Test. YT is bundled with the Yahoo! User Interface Library (YUI). To quote the YUI site:

YUI Test is a testing framework for browser-based JavaScript solutions. Using YUI Test, you can easily add unit testing to your JavaScript solutions. While not a direct port from any specific xUnit framework,YUI Test does derive some characteristics from nUnit and JUnit.

Key features of YUI Test include:

  1. Rapid creation of test cases through simple syntax.
  2. Advanced failure detection for methods that throw errors.
  3. Grouping of related test cases using test suites.
  4. Asynchronous tests for testing events and Ajax communication.
  5. DOM Event simulation in all A-grade browsers.
    YUI Test has been available since July 2007 (YUI 2.3.0), and made “GA” grade in February 2008 (YUI 2.5.0). The YT framework was created by Yahoo! engineer Nicholas C. Zakas. It’s regularly released and maintained with the rest of the library, and its distributed under the library’s BSD license. (All together, there seem to be about sixteen developers on the YUI team, maintaining about thirty components).

(!) Note that YUI Test can be used to test any JavaScript code – the application doesn’t need to be based on YUI to use YUI Test.

One of the pleasures of YUI Test is that it can use the YUI TestLogger as a test harness.

TestLogger is a subclass of YUI Logger, which can be used for general-purpose JavaScript logging and debugging, giving us two great capabilities in one flexible component. YUI Test can also be used in collaboration with the new YUI Profiler (another Zakas creation) to create performance-based tests.

Trip the Rift

Unit testing conventional, classical code often relies on exercising the “API Contract”. If we pass certain parameters to method, the method should return a certain result, or raise a certain exception. Since, JavaScript is event-driven, in order to determine the outcome of a method, we often need to know what events it raises. Meanwhile, in an Ajax application, there can be a disconnect between when a method is called and when the event is ultimately reaised. YUI Test helps us bridge the gap with a “wait/resume” feature. A test can subscribe to an event, and call “resume” in the event handler. When the test reaches the point where an action might take an indeterminate amount of time, we can call “wait”, and the test continues when the event fires.

For example, here’s a test that calls a time-consuming animiation routine. The test registers an event handler, starts the animation, and waits for the event to fire. When the animation completes, the test confirms that the routine accomplished the expected result.

YAHOO.namespace(“example.yuitest”); YAHOO.example.yuitest.AsyncTestCase = new YAHOO.tool.TestCase({ name : “Animation Tests”, testAnimation : function (){ var Assert = YAHOO.util.Assert; var YUD = YAHOO.util.Dom; var myAnim = new YAHOO.util.Anim(‘testDiv’,

{ width: { to: 400 } }, 3, YAHOO.util.Easing.easeOut); myAnim.onComplete.subscribe(function(){ this.resume(function(){ Assert.areEqual(YUD.get(“testDiv”).offsetWidth,

400, “Width of the DIV should be 400.”); }); }, this, true); // Start the animation and wait for the resume function myAnim.animate(); this.wait(); } }); YAHOO.util.Event.onDOMReady(function (){ var logger = new YAHOO.tool.TestLogger(“testLogger”); YAHOO.tool.TestRunner.add(YAHOO.example.yuitest.AsyncTestCase); // Run the tests when DOM is ready YAHOO.tool.TestRunner.run(); });

Not every test needs to use wait/resume, but, when we do, it’s an indispensible feature.

Be Assertive

Asynchronous or not, essentially, unit testing is about making assertions. We unit test by invoking a method and passing in known parameters and observing the outcome. We might expect the method to return a simple value, or another object, like a Date Type, with certain attributes set to certain values. Or, we might expect the method to fail and raise an exception, or to succeed and raise and event.

Since we’re talking JavaScript, YUI not only supports all the usual assertions, but type cohersion to boot.

var oTestCase = new YAHOO.tool.TestCase({

name: “TestCase Name”,

testEqualityAsserts : function () {

var Assert = YAHOO.util.Assert;

Assert.areEqual(5, 5); //passes

Assert.areEqual(5, “5”); //passes

Assert.areNotEqual(5, 6); //passes

Assert.areEqual(5, 6, “Five was expected.”); //fails

}

});
For more precise testing, YUI Test provides for Sameness Assertions.
var oTestCase = new YAHOO.tool.TestCase({

name: “TestCase Name”,

testSamenessAsserts : function () {

var Assert = YAHOO.util.Assert;

Assert.areSame(5, 5); //passes

Assert.areSame(5, “5”); //fails

Assert.areNotSame(5, 6); //passes

Assert.areNotSame(5, “5”); //passes

Assert.areSame(5, 6, “Five was expected.”); //fails

}

});
Since JavaScript is loosely typed, asserting data types is a common need. YUI Test provides assertions for all the usual suspects; Array, Boolean, Function, Number, Object, String. To close the loop, an isTypeOf assertion interprets the data type as string.
var oTestCase = new YAHOO.tool.TestCase({

name: “TestCase Name”,

testTypeOf : function () {

var Assert = YAHOO.util.Assert;

Assert.isTypeOf(“string”, “Hello world”); //passes

Assert.isTypeOf(“number”, 1); //passes

Assert.isTypeOf(“boolean”, true); //passes

Assert.isTypeOf(“number”, 1.5); //passes

Assert.isTypeOf(“function”, function(){}); //passes

Assert.isTypeOf(“object”, {}); //passes

Assert.isTypeOf(“undefined”, this.blah); //passes

Assert.isTypeOf(“number”, “Hello world”, “Value should be a number.”); //fails

}

});
A companion assertion, isInstanceOf, can be used to evaluate object types (Array, Function, Object). Other assertions are available for evaluating JavaScript-isms like NaN, Undefined, and truthiness.

Finally, YUI Test also supports date and time assertions, forced failures, skipping tests, and test suites.

Push the Envelope

Aside from exposing the usual xUnit API, YUI Test goes a step further, and provides support for UserActions and Asyncronous Tests.

  • User Actions are simulated user-initiated events that can be used to test how scripts react to mouse or keyboard events.
  • Asyncronous Tests can be programmed to pause for a certain amount of time (while an out of process action occurs), or to pause until an event handler in the test script calls a “resume” method.
    Whether you’ve outgrown JsUnit, or whether you’re finally ready to start unit testing JavaScript for the first time, be sure to give YUI Test a try.

More about YUI Test

More about JsUnit

More about Open Source Testing Tools

Haromonizing the Good Parts

“Sometimes a step backward is a step in the right direction …”

Over the summer, there have been two loosely related events on the JavaScript landscript:_ ECMAScript Harmony _and JavaScript: The Good Parts.

ECMAScript Harmony

In the land of JavaScript, the “tyranny of the installed base” rules supreme. A key frustration of JavaScript developers is that platform innovations are metered by the glacial rate at which the marketplace upgrades browser clients.

Ironically, JavaScript pundits have been equally concerned about there being too much innovation in the ECAMScript 4 specification. The new specification includes ambitious notions like packages, namespaces and early binding.

In August, the working group met in Oslo and arrived at a new focus for the future of JavaScript, dubbed the ECMAScript Harmony project. The core of ES Harmony can be expressed in a set of four goals.

  1. Focus work on ECMAScript 3.1 with full collaboration of all parties, and target two interoperable implementations by early next year.
  2. Collaborate on the next step beyond ECMAScript 3.1, which will include syntactic extensions but which will be more modest than ECMAScript 4 in both semantic and syntactic innovation.
  3. Some ECMAScript 4 proposals have been deemed unsound for the Web, and are off the table for good: packages, namespaces and early binding. This conclusion is key to Harmony.
  4. Other goals and ideas from ECMAScript 4 are being rephrased to keep consensus in the committee; these include a notion of classes based on existing ES3 concepts combined with proposed ECMAScript 3.1 extensi
    For more about ECMAScript Harmony, visit John Resig’s blog.

JavaScript: The Good Parts

Admist the ES4 turmoil, workers at both Mozilla and Yahoo! have advocated moderation. John Resig, of Mozilla, went on a ES4 speaking tour to raise awareness, and Douglas Crockford, of Yahoo!, brought out JavaScript: The Good Parts, a testament to the doctine of “less is more”.

In “The Good Parts”, Crockford walks through both the good and the bad of JavaScript, pointing out best practices to embrace and design flaws to avoid. While Crockford tries to “accentuate the positive”, one can’t help but notice that many best practices are driven by design flaws.

Some Design Flaws

  • Reliance on global variables weakens the resiliency of programs [p25].
  • Inner variables set to functions are bound to the global object (not the “this” of the outer function) [p28].
  • Arguments are not really an array [p31].
  • Support for block syntax implies a block scope, but there is no block scope [p36].

Some Best Practices

  • Reduce your global footprint to a single name (like YUI’s YAHOO namespace) [p26].
  • Throw exceptions when a mishap is detected [p32].
  • Declare all variables used in a function at the top of the function body [p36].
  • Use the module pattern to eliminate the use of global variable [p41].
    Crockford is presenting a talk on the Good Parts at the Ajax Experience 2008 in Boston on September 29th. Sadly, his talk is up against my own talk “Ajax Testing Tool Review”. I just hope someone shows up for mine …

Preaching to the Choir

At VanDamme Associates, we make good use of John Resig’s JQuery library and Yahoo’s YUI library in our Ektron-based web applications. Together, these packages already deliver the same utility that an overly-ambitous ES4 might provide. A kinder, gentler ES4 means a more stable and robust development environment for us and our clients. To quote a famous, if fictional, engineer: “The more they fancy up the plumbing, the easier it is to gum up the works.”

Ajax Experience 2008 - More Ted, 'nuff said

I’ll be giving three – count ‘em three – presentations at the Ajax Experience at the end of September. Two talks are Struts-related reprisals form last year, and the third talk, new this year!, dives into popular tools for testing Ajax applications.

Hope to see you there!

Ajax Testing Tool Review

Not long ago, testing Ajax components meant play-testing a page by hand. Today, there are a growing number of tools we can use to simplify and automate Ajax testing.

In this session we will cover when to test, what to test and how to test Ajax components. You learn how to create automatic tests with various tools, including YUI Test, OpenQA Selenium and TIBCO Test Automation Kit, and how to use Ajax testing tools with IDEs and Continuous Integration systems.

In this session, you will learn:

  • When, where and how to test Ajax components;
  • How to create automatic tests with various tools;
  • How to use Ajax testing tools with IDEs and Continuous Integration systems.

Struts on Ajax: Retrofitting Struts with Ajax Taglibs

Struts is Java’s most popular web framework. Ajax is the web’s hottest user interface. What happens when we put Struts on Ajax?

In this session, we stir some Ajax wizardry into a conventional Struts application, without all the sweat and bother of writing our own JavaScript. Struts 1 and Struts 2 both support Ajax taglibs that look and feel just like ordinary JSP tags. If it’s just a little bit of Ajax that you want, these tags will get you around the learning curve in record time.

During the session, we will cover

  • Using the Java Web Parts taglib with Struts 1
  • Using the Ajax YUI plugin with Struts 2
    Who should attend: Struts developers who would like to utilize Ajax with existing applications, and Ajax developers who would like to utilize Struts as a backend.

To get the most from this session, some familiarity with Struts or a similar framework is helpful.

To register, visit Ajax Experience site.

Ajax on Struts: Coding an Ajax Application with Struts 2

Ajax is the web’s hottest user interface. Struts is Java’s most popular web framework. What happens when we put Ajax on Struts?

In this session, , we look at writing a new Struts 2 application from square one, using the Yahoo User Interface (YUI) Library on the front end, and Struts 2 on the backend. YUI provides the glitz and the glamour, and Struts 2 provides the dreary business logic, input validation, and text formatting.

During the session, we will cover

  • How to integrate an Ajax UI with Struts 2
  • Basics of the Yahoo User Interface (YUI) Library
  • Business services Struts can provide to an Ajax UI
    Who should attend: Ajax developers who would like to utilize Struts as a back-end, and Struts developers who would like to utilize Ajax as a front-end.

To get the most from this session, some familiarity with an Ajax library, like YUI or Dojo, is helpful.

Visit the Ajax Experience site to register.

The Dark Side of the Internet Lecture, Tuesday, June 24th at 6PM in Rochester NY

On Tuesday, June 24, at 6:00 pm, the BlueTie Unlimited Bandwidth Lecture Series will host Mr. Scott Forbes as our guest lecturer. This lecture will deal with the prevention of the dangers found on the Internet including topics such as; SPAM/Chain Letters,Virus/hackers, Hoax/Urban Legends, Identity theft, cyber-terrorism, cyber-bullies, and ebay/internet scams. Mr. Forbes has over 30 years experience in the Information Technology field and currently teaches IT at Nazareth College where he includes Internet security as part of his curriculum.

Please join us at the BlueTie Campus, 1050 Pittsford-Palymra Road, Pittsford NY on June 24th. Refreshments will be served and seating is limited. Please RSVP 585-586-2000 if you plan on attending.