Vanilla JS Testing — Part II
Yesterday I’ve posted about console.assert and code coverage and its badge, today I’d like to quickly walk through few lines of code that can bring literally all you need to test your application, library, or framework.
A Minimalistic Wrap For console.assert
Claudio made a point in this tweet, and I kinda agreed with him:
huge downside of not using frameworks: unwrapped calls to console.assert will break the code at the first false assertion
But as shown in the previous tweet, it took pretty much nothing to circumvent the issue he addressed. In order to avoid code breaking and stopping at the very first falsy assertion, all we need is a minimal wrap.
Moreover, if our test file is executed through some CLI, it’s important to communicate possible failures at the very end of the execution.
That’s pretty much it for synchronous tests, but we all know JavaScript is famous for its multitude of asynchronous features, isn’t it?
No panic then, we can litterally provide asynchronous testing in 5 LOC!
At this point, testing something would be as straight forward as writing:
OK For NodeJS, but What About Browsers?
Differently from node, browsers don’t throw exceptions on console.assert
.
That means that the catch
part of our wrapper will never be reached, and as little as it is our wrapper already, that’s just OK.
However, in case we’d like to see also correct tests printed as valid, and with a check ✔ sign, as opposite to a failed ✖ one, like it is for common testing frameworks, we need to slightly pollute our initial wrapper, making it also universally usable through good old ES3 syntax.
That’s it, the initial Claudio idea of having a minimal testing framework in few lines of code, has been summarized, with asynchronous testing ability too, in this ultimate gist.
Tressa.JS
Having some gist in the wild to copy and paste is cool, but having an official repository is even better. The tressa repository idea is to bring the minimal simplicity I’ve just described, into a regular npm package.
There is only one tiny extra feature in it, you can specify a tressa.title(testName)
upfront, or use its Markdown capable logger, and obtain console results like the following one.
