HTML and CSS Reference
In-Depth Information
1.1.1 Unit Testing Frameworks
Unit tests are usually written using a unit testing framework, although that is not
strictly necessary. In this chapter we'll focus on the concept of unit tests, working
through the different aspects of writing and running them. We'll defer the discussion
of actual testing frameworks for JavaScript to Chapter 3, Tools of the Trade .
It's likely that you've already written more than a few unit tests, even if you
have never done any structured unit testing. Whenever you pop up a console in
a browser (e.g., Firebug, Safari's Inspector or others) to debug or play live with
your code, you probably issue some statements and inspect the resulting state of
the involved objects. In many cases this is unit testing, only it isn't automated and
it's not reproducible. We'll work through an example of this kind of testing and
gradually formalize it as an xUnit test case .
xUnit is a common way to refer to test frameworks that are either a direct port
of JUnit, or more loosely based on the ideas and concepts in it—or, more correctly,
the ideas and concepts in SUnit, the Smalltalk testing framework. Kent Beck, the
father of extreme programming, played an integral part in the creation of both these
frameworks, and even though SUnit was the first implementation, JUnit has done
the most in terms of popularizing the pattern.
1.1.2 strftime for JavaScript Dates
Many programming languages provide a strftime function or similar. It operates
on a date or timestamp, accepts a format string, and produces a formatted string
that represents the date. For example, in Ruby, strftime is available as a method
on time and date objects, and Listing 1.1 shows an example of its use.
Listing 1.1 Time#strftime in Ruby
Time.now.strftime("Printed on %m/%d/%Y")
#=> "Printed on 09/09/2010"
Listing 1.2 shows an early attempt at implementing strftime for JavaScript.
It's implemented on Date.prototype which makes it available as a method on
all date objects. Don't despair should you find it hard to understand all the details
of the code in this chapter. Concepts are more important than the actual code, and
most advanced techniques will be discussed in Part II, JavaScript for Programmers .
Listing 1.2 Starting point for strftime for JavaScript
Date.prototype.strftime = (function () {
function strftime(format) {
 
Search WWH ::




Custom Search