Tuesday, April 24, 2007

JsUnit integration

Today we tried to integrate JsUnit. One of issues was how to execute JavaScript tests within other unit tests (PHPUnit of version 2).

The tests must be easy to execute, but at first sight it looks like you should insert urls to your tests in JsUnit runner and click Run button every time to look at test results. Fortunately JsUnit understands query strings: testPage and autoRun. It makes life much better...

The first attempt was calling JsUnit runner via iframe in the test result page. It was unsuccessful because the runner uses some top elements from the page. And if the page is displayed in the iframe then the elements are got from PHPUnit test page result, not from runner's page itself. So the attempt was failed.

The next thought was to open test pages in JavaScript popup windows. We have done the following: install the JsUnit into tests/js/jsunit folder and create a tests/JavaScriptTest.php file with the test method:
function testJavaScript() {
$jsTestPath = $_SERVER["SERVER_NAME"] .

dirname($_SERVER["SCRIPT_NAME"]) . '/js';

$tests = array();
foreach (glob("js/*.html") as $filename) {
$tests[] = basename($filename);
}

echo "<script language='JavaScript'>\n";
foreach ($tests as $test) {
$fullPath = "http://{$jsTestPath}" .
"/jsunit/testRunner.html?testPage=" .
"{$jsTestPath}/{$test}&autoRun=true";

echo "window.open('{$fullPath}', '{$test}', " .
"'location=1,status=1,scrollbars=1,width=950,height=500');\n";
}
echo "</script>\n";
}
It just scans for test pages in tests/js folder and generate JavaScript for opening them in a separate popups. We found it is very useful. Every time you run your test suites it execute JavaScript tests too. If a test is failed you can fix the code and run the failed test page until success without restarting of server side tests.

It is rather hard to say how to use JsUnit for testing AJAX stuffs or for visual (DOM) manipulations. Because it requires to create rather expansive environment. But if you have pure calculation JavaScript methods (for example something like hex2rgb color convertion, etc) then it could add a lot of stability to your project.

Other note is the JavaScriptTest should not be executed from your Cruise Control system (in case you don't use JsUnit server of course).

0 comments: