Why unit testing?
There are many test packages for Node (my favorite is ava) and there are also a few for Apps Script but I couldn’t find one that was exactly what I was after, so I’ve released the one I use as a library. Unit testing your code as you go along will make it easier to find errors right away, check results are as expected, and keeping a running repertoire of tests ensures that you don’t break anything when you make changes.
Here’s how it works.
Initializing Unit tester
You’ll need the bmUnitTest library – library details at the end of this post.
There are a number of behavioral options, but we’ll deal with them throughout the course of this library. This library is deliberately simple to use straight out of the box.
Tests are best organized into sections – so you can keep your tests all together but easily skip irrelevant tests when required. A test section looks like this
is (expected, actual, options) – it passes if expected equals actual
not (expected, actual. options) – it passes if expected not equals actual
The definition of ‘equals’ is the key to the simplicity of this library.
Sections and tests can have descriptions. Here’s a more descriptive version of those tests and section
Undefined and null
You normally don’t want to see an undefined anywhere, but a null is acceptable. By default Unit always treats undefined as an error, and null as a normal object. As usual this is modifiable via options at instance, section or test level. In these examples the usual equality tests are modified by whether undefined and null are ever acceptable values.
You’ll have noticed a number of options specified in the tests so far. A full list of available options is given at the end of this article. Here’s some examples of overriding section level options with test level options.
Test return object
A test will return an object describing the test and the result, which may be useful for further processing. The UnitResult response look like this
Skipping tests and sections
Sometimes you might want to skip sections or individual tests. You can use the skip option to temporary disable a section or a test
Skipping a section
When a section is skipped it is reported but not executed
Skipping a test
When an individual test is skipped it is completely ignored
Once you’ve established a test set you probably will only want to see the reports of the failures. You can use the showErrorsOnly option to do that at instance, section or individual test level. Let’s rerun all the tests in this article, but this time only show the errors.
Test set summary
At the end of it all, you can request a report of how it all went
List of methods and properties
Here’s the skeleton class. You can call any of these if you need some more fine control of the tests. The full code is on github or via the IDE at the end of this article
library ID 1zOlHMOpO89vqLPe5XpC-wzA9r5yaBkWt_qFjKqFNsIZtNJ-iUjBYDt-x