Javascript Testing

The Closure Library contains a framework for jsunit-style unit tests.

Clover features web based and command line test runners.

Writing a Test case

The convention for unit testing a file of JavaScript code is to create the test case in a file of the same name, except with a _test.js suffix.

For example, to create a unit test for goog.string, which is defined in string.js, the test code should be written in string_test.js. Here is a code sample from such a string_test.js file:

goog.require('goog.string');
goog.require('goog.testing.jsunit');

var testStartsWith = function() {
  assertTrue('Should start with \'\'', goog.string.startsWith('abcd', ''));
  assertTrue('Should start with \'ab\'', goog.string.startsWith('abcd', 'ab'));
};

Running a individual Test (via the browser)

  1. Visit the configuration listing page at http://localhost:2323/.
  2. Follow the “List Test Files” link for the configuration you want to test.
  3. There should be a link for each test file. Follow the link to the test file to run a test runner on that file.
  4. Passing tests are displayed in green while failing tests are displayed in red.

TODO: Running a test via the command line

The command line test runner uses a webdriver instance to run and check your tests.

The server must be started before running tests:

clover serve <config file>

The following command should run tests using the server:

clover test <config id> <path to test file>

Running All Tests

To run all of your tests visit the configuration listing page and click “Run Tests” for a configuration.

This will bring up a goog.testing.MultiTestRunner configured to runs all of your tests.

Writing Asynchronous Tests

Globals named AsyncTestCase and DeferredTestCase are provided.

These are the instance of goog.testing.DeferredTestCase that are used to run your page.

To override this use the following after at the head of your test file:

var AsyncTestCase = new goog.testing.AsyncTestCase.createAndInstall(CLOVER_TEST_TITLE)

The global CLOVER_TEST_TITLE is the test title provided by the clover server (the file path of the test).