I’m going to share some stuff that I’m reading, but, I want to give full credit to Manning and John Resig, lest someone mistake me for already being this smart (doubtful).
The two keys for writing good code are testing and debugging. The skill you need for any language is to learn the techniques employed by folks smarter than you for how to make sure your code tests out accurately given the complexity of the environment it has to run in. In the case of JS, you got about 4 major browser developers (not including mobile) with 2-3 to be most concerned about.
Let’s start with Testing…
Resig states there are two types of tests, constructive and destructive. Regardless, there are a few points he makes, which I fully back from my 15 years of software testing and automated test software development that you must remember:
- Your tests should be highly reproducible. It should be possible to run your test over and over and never receive a different result. Additionally this includes making sure that your tests are not dependent upon outside issues (like network or CPU load)
- Break your tests apart. Try not to make the results from one test be dependent upon another. Break tests down into their smallest possible unit (which helps you to determine the exact source of a bug when an error occurs.
Deconstructive Test Cases
Constructive Test Cases
Start from a known, reduced case and build up until you’re able to reproduce the bug. You’ll need some test files from which to build and a way to generate these new tests with a clean copy of your code.
For example, create your reduced test case using a few html files with minimum functionality already included (one for DOM manipulation, one for Ajax tests, one for animations, etc.)
Reduced DOM test case for jQuery:
To generate a test with a clean copy of the code base, Resig provides a shell script to check the library, copy over the test case and build the test suite:
#!/bin/sh # Check out a fresh copy of jQuery
git clone git://github.com/jquery/jquery.git $1
# Copy the dummy test case file in
cp $2.html $1/index.html
# Build a copy of the jQuery test suite
cd $1 && make
Run this script like so:
./gen.sh mytest dom
(which would pull in the DOM test case from dom.html).
Another alternative entirely is to use a pre-build service designed for create simple test cases. One such service is JSBin.com, useful for building a test case that then becomes available at a unique URL.
With the tools and knowledge in place for figuring out how to reduce a test case we should start to build a test suite around it so that it becomes easier to run these tests over-and-over again.
Next post: Picking a Test Suite