mocha-foam is a plugin for mocha to support property-based testing in BDD tests using fast-check arbitraries.
The library provides a wrapped version of it
that runs the tests repeatedly over a number of generated values, using
fast-check’s runner and arbitraries. This is a very small library, arguably too small, but I wanted to make the
fast-check runner fit better into mocha’s BDD-style tests. Rather than put the arbitrary within the assertion, like some
libraries, this puts the entire test within the arbitrary and allows more setup code, like creating models or calling
utility functions on the values.
Property-based testing is a great way to find bugs you were not expecting, especially when dealing with user input. I created mocha-foam to improve the tests for my js-utils library, which provides a number of generic helper functions.
Status
mocha-foam should be considered a beta release and should not be deployed to production, although as a testing library it should never be deployed to begin with. It works correctly and most of the initial features have been implemented, but I cannot guarantee that the API is stable yet.
Example
Tests can be run over
a variety of values within a test suite, so the plugin provides a wrapped version of mocha’s
it
that executes the given test for each value of the arbitraries:
describe('the unit under test', () => {
over(strings(), (it) => {
it((value: string) => {
// some test using value
});
});
});
Further Reading
There are property-based testing libraries available for a few other languages, including the fast-check library that mocha-foam wraps and Quickcheck library that popularized the concept.