Douglas Crockford has released JSCheck, a lightweight JavaScript testing tool. Inspired by the Haskell library QuickCheck, JSCheck will generate random test cases against the specified properties of a system, function, or object. The project introduces a JSC global which includes:

The claim function takes a name, a predicate function, and an array of specifiers.

The predicate function should return true if a case passes. It will take a list of arguments that is generated by the array of specifiers. The array of specifiers looks like a type declaration for the predicate function.

It returns a function that can be processed by JSC.check.

To test the following function:

function le(a, b) {
    return a <= b;
}

one might construct a test as follows:

JSC.test("Less than", function (a, b) {
    return le(a, b);
}, [
    JSC.integer(10),
    JSC.integer(20)
], function (a, b) {
    if (a < b) {
        return 'lt';
    } else if (a === b) {
        return 'eq';
    } else {
        return 'gt';
    }
});

The calls to JSC.integer will return an integer between 1 and the supplied argument. The JSC object provides a lengthy list of these specifier functions, including the ability to compose complex array templates:

JSC.array([
    JSC.integer(),
    JSC.number(100),
    JSC.string(8, JSC.character('A', 'Z'))
])

… which will yield something similar to

[3,21.228644298389554,"TJFJPLQA"]
[5,57.05485427752137,"CWQDVXWY"]
[7,91.98980208020657,"QVMGNVXK"]
[11,87.07735128700733,"GXBSVLKJ"]
...

Check out the source on GitHub and the included HTML docs, or you can view them in the GitHub pages branch of my fork view them on www.jscheck.org.


Have comments? Send a tweet to @TheChangelog on Twitter.

Subscribe to The Changelog Weekly – our weekly email covering everything that hits our open source radar.