A DSL for testing in JavaScript

October 12, 2016

Given an array:

var xs = [2, 4, 8, 16];

Write from scratch a library to check the values of elements within it:

forArray(xs).elemAt(3).shouldBe(equalTo(16));
// throws no exceptions

// forArray(xs).elemAt(2).shouldBe(equalTo(16));
// throws "expected 16 at index 2, but found 8"

// forArray(xs).elemAt(4).shouldBe(equalTo(16));
// throws "expected 16 at index 4, but the largest valid index is 3"

Bonus

Add support for checking other characteristics of the elements:

forArray(xs).elemAt(3).shouldBe(atLeast(16));
// throws no exceptions

// forArray(xs).elemAt(2).shouldBe(greaterThan(8));
// throws "expected a value greater than 8 at index 2, but found 8"
forArray(xs).elemAt(3).shouldBe(even());
// throws no exceptions

// forArray(xs).elemAt(3).shouldBe(odd());
// throws "expected an odd number at index 3, but found 16"