mocha-foam

property based testing for mocha using fast-check
July 20, 2021
typescript library mocha testing


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.


Related Posts

noicejs

DI library with no dependencies
February 8, 2016
typescript dependency-injection library

textual-engine

text adventure engine
May 12, 2021
typescript cli ink react text-adventure

cautious-journey

state machine for Github/Gitlab issue labels
August 11, 2020
typescript github gitlab state-machine