Unit testing library functions

Hey all,

I’ve been working on refactoring some of the code behind a moderately-complex Tinderbox document. As I’ve been working through my code, one of the affordances I’ve missed from other programming environments is support for unit testing. To address my immediate needs I’ve written a few functions that can be added into the Library and used in other function-defining notes. I hope some of you might find them useful!

(For those not familiar with functions, see this aTbRef page.)

function failTest(message) {
  $TestMessages = $TestMessages + message;
  $Color = "red";
}

function resetTests() {
  $TestMessages = "";
  $Color = "green";
}

function assertEquals(actual, expected) {
  if(actual != expected) {
    failTest("Failed assertion: " + actual + " does not equal " + expected);
  }
}

function assertTrue(actual) {
  assertEquals(actual, true);
}

function assertFalse(actual) {
  assertEquals(actual, false);
}

function assertNotEquals(actual, sentinel) {
  if(actual == sentinel) {
    failTest("Failed assertion: " + actual + " is equal to " + sentinel);
  }
}

resetTests();
failTests("Testing the fail function");
assertEquals(false, true);
assertNotEquals(true, true);

Notes containing failing tests will be colored red, while notes with all tests passing are green:

Messages from failing assertions are aggregated into the $TestMessages user property:

It’s not very fancy at the moment but the basics are there, and it should be clear how to extend the functionality to add more features as needed. Enjoy!

4 Likes

Excellent! I’m working, as it happens, on a better way to display messages like these, and also thinking about ways to make it easier to package functionality like this an install it into new documents…

2 Likes