Property-Based Testing for JavaScript/TypeScript

4.7.0 · active · verified Sun Apr 19

fast-check is a property-based testing framework for JavaScript and TypeScript, inspired by Haskell's QuickCheck. It enables developers to define properties about their code and automatically generates diverse inputs to test these properties, identifying edge cases that traditional example-based testing might miss. The current stable version is 4.7.0. The project maintains an active release cadence, with continuous development across its core library and various test runner integrations. Key differentiators include its robust shrinking capabilities, which minimize counterexamples to help pinpoint bugs, an extensive set of built-in arbitrary data generators, and comprehensive TypeScript support. It integrates seamlessly with popular testing frameworks like Mocha, Jest, Vitest, and Ava via dedicated adapter packages, though users should be aware of recent changes in module support for these adapters.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates a basic integration of fast-check with Mocha, defining and asserting properties using arbitrary string generation.

import fc from 'fast-check';

// Code under test
const contains = (text, pattern) => text.indexOf(pattern) >= 0;

// Properties
describe('properties', () => {
  // string text always contains itself
  it('should always contain itself', () => {
    fc.assert(fc.property(fc.string(), (text) => contains(text, text)));
  });
  // string a + b + c always contains b, whatever the values of a, b and c
  it('should always contain its substrings', () => {
    fc.assert(
      fc.property(fc.string(), fc.string(), fc.string(), (a, b, c) => {
        // Alternatively: no return statement and direct usage of expect or assert
        return contains(a + b + c, b);
      }),
    );
  });
});

view raw JSON →