This article was translated from Japanese by AI and may contain inaccuracies. For the most accurate content, please refer to the original Japanese version.
江戸切子のグラスのイラスト

Getting Started with fast-check: Property-Based Testing in TypeScript

As AI-generated code becomes common, property-based testing, which checks properties code must satisfy rather than specific examples, is drawing renewed attention. This article covers the basics using the TypeScript library fast-check with Vitest.

Now that AI coding agents can produce implementations and unit tests in a short amount of time, verifying that the code they write actually meets the specification has become more important than ever. In traditional unit testing, developers or AI agents pick a handful of concrete input and expected-output pairs and check them. This approach is called example-based testing, and it is effective for documenting representative cases of a specification.

On the other hand, if you have asked an AI agent to write tests, you have probably seen it produce tests that simply trace the existing implementation. Because AI tends to focus on getting tests to pass, it often generates inputs that are chosen to pass verification, leaving the essential properties of the specification untested. And as the number of input combinations grows, there is a limit to how many edge cases a human can enumerate by hand.

Against this backdrop, property-based testing (PBT) is drawing attention again. Instead of concrete input/output examples, you define "properties that always hold for any valid input," and the framework searches for counterexamples using large numbers of automatically generated inputs. A research post from Anthropic also reports how combining Claude with a property-based testing framework uncovered edge-case bugs in open-source projects such as NumPy and SciPy.

This article covers fast-check, a property-based testing framework written in TypeScript. While walking through the basic concepts of property-based testing, we will look at implementation examples that combine fast-check with Vitest.

What Is Property-Based Testing?

Property-based testing traces its roots to QuickCheck, a Haskell tool published by Koen Claessen and John Hughes in 2000. What sets it apart from example-based testing is what you write in your test code.

For example, consider testing a function sortAscending that sorts an array of numbers in ascending order. With example-based testing, you write pairs of concrete inputs and expected values.

expect(sortAscending([3, 1, 2])).toEqual([1, 2, 3]);
expect(sortAscending([])).toEqual([]);

However, tests that only cover representative cases like these have pitfalls that are easy to miss. For instance, if you forget to pass a comparison function to JavaScript's Array.prototype.sort(), the elements are sorted lexicographically as strings. Single-digit positive integers like [3, 1, 2] cannot catch this bug; it only surfaces with arrays such as [10, 2] or arrays containing negative numbers. Likewise, arrays with duplicate elements, extremely large numbers, and side effects such as destructively modifying the original array will slip through unless you happen to think of them as test cases in advance.

Property-based testing, by contrast, describes rules (properties) shared by all valid inputs, such as "for any array of numbers, the returned array has the same length as the original and every pair of adjacent elements is in ascending order" or "sorting twice gives the same result as sorting once." The framework then automatically generates random inputs and runs the test repeatedly, trying to find an input that breaks the rule (a counterexample).

Property-based testing consists mainly of the following three elements:

  • Arbitrary: Bundles the generation of test inputs with the shrinking mechanism that makes inputs smaller and simpler when a test fails
  • Property: A function that receives generated inputs and verifies the properties the target code must satisfy
  • Shrinking: When a test fails, the process of stripping unnecessary parts from a complex, randomly generated counterexample and narrowing it down to the minimal counterexample that still reproduces the failure

Note

Rather than plain uniform randomness, fast-check uses biased generation by default, prioritizing edge cases where bugs tend to hide, such as 0, empty strings, empty arrays, and extreme integers.

Setting Up fast-check and Basic Usage

fast-check is independent of any test runner. You can use it with any test framework, including Vitest, Jest, and the built-in Node.js test runner. In this article, we will use Vitest.

First, install fast-check and vitest as dev dependencies.

npm install --save-dev fast-check vitest

Next, let's write a minimal property-based test for the sortAscending function from earlier. We define the Arbitrary and the verification function with fc.property, and run it with fc.assert.

src/basic.test.ts
import fc from "fast-check";
import { describe, expect, it } from "vitest";
 
function sortAscending(values: readonly number[]): number[] {
  return [...values].sort((a, b) => a - b);
}
 
describe("basic property-based tests", () => {
  it("the sorted array has the same length as the original and is in ascending order", () => {
    fc.assert(
      fc.property(fc.array(fc.integer()), (numbers) => {
        const sorted = sortAscending(numbers);
 
        expect(sorted).toHaveLength(numbers.length);
        for (let i = 1; i < sorted.length; i++) {
          expect(sorted[i - 1]).toBeLessThanOrEqual(sorted[i]);
        }
      }),
    );
  });
 
  it("sorting twice gives the same result as sorting once (idempotency)", () => {
    fc.assert(
      fc.property(fc.array(fc.integer()), (numbers) => {
        const once = sortAscending(numbers);
        const twice = sortAscending(once);
 
        expect(twice).toEqual(once);
      }),
    );
  });
});

In this code, fc.array(fc.integer()) builds an Arbitrary that generates arrays of type number[]. By default, fc.assert generates 100 random inputs and runs the callback for each one. The test is considered failed if the callback throws an exception (that is, a Vitest expect fails) or returns false.

When you run npx vitest run, each test case is checked against 100 automatically generated arrays (including empty arrays, negative numbers, duplicate values, and 32-bit integer boundaries), and all of them pass.

 RUN  v5.1.2
 
 ✓ src/basic.test.ts (2 tests) 10ms
   ✓ basic property-based tests (2)
     ✓ the sorted array has the same length as the original and is in ascending order 7ms
     ✓ sorting twice gives the same result as sorting once (idempotency) 2ms
 
 Test Files  1 passed (1)
      Tests  2 passed (2)
   Start at  21:03:07
   Duration  124ms (transform 41%, import 32%, tests 23%, worker 4%)

If you take an excerpt of the arrays actually generated by fc.sample(fc.array(fc.integer()), { numRuns: 100 }), you can see that the inputs automatically include empty arrays, negative numbers, 0, the maximum 32-bit signed integer (2147483647), and more.

[]
[-20, 1789811753]
[313098291, -936321574, 2147483647]
[-938247747, -4, -1940970518, 1755819559, -1108417337, -2147483647, -2142699944, 16, 0, 630822387]
[1, -317889584, 1702336078]

Generating Domain Data with Custom Arbitraries

Once you have the basic idea from a primitive array example like sorting, the next step is testing the domain objects that real applications deal with. Here, we will use the "logic that calculates the discounted total from a list of items and coupons" in an e-commerce shopping cart as our example.

First, let's define the types for items and coupons, along with a function that calculates the subtotal. There are two kinds of coupons: percentage, which discounts by a percentage, and fixed, which subtracts a fixed amount.

src/cart.ts
export type CartItem = {
  id: string;
  unitPrice: number;
  quantity: number;
};
 
export type Coupon =
  | { type: "percentage"; percent: number }
  | { type: "fixed"; amount: number };
 
export function calculateSubtotal(items: readonly CartItem[]): number {
  return items.reduce((sum, item) => sum + item.unitPrice * item.quantity, 0);
}

When testing business logic, you need to automatically generate large numbers of valid inputs that satisfy the domain's preconditions, such as unit prices of at least 1 yen and discount rates between 0% and 100%. To generate test data for these types, you build custom Arbitrary instances by combining the built-in Arbitrary functions that fast-check provides.

import fc from "fast-check";
import type { CartItem, Coupon } from "./cart.js";
 
const cartItemArb: fc.Arbitrary<CartItem> = fc.record({
  id: fc.string({ minLength: 1, maxLength: 12 }),
  unitPrice: fc.integer({ min: 1, max: 100_000 }),
  quantity: fc.integer({ min: 1, max: 50 }),
});
 
const percentageCouponArb: fc.Arbitrary<Coupon> = fc.record({
  type: fc.constant("percentage" as const),
  percent: fc.integer({ min: 0, max: 100 }),
});
 
const fixedCouponArb: fc.Arbitrary<Coupon> = fc.record({
  type: fc.constant("fixed" as const),
  amount: fc.integer({ min: 0, max: 50_000 }),
});
 
const couponArb: fc.Arbitrary<Coupon> = fc.oneof(
  percentageCouponArb,
  fixedCouponArb,
);
 
const cartItemsArb = fc.array(cartItemArb, { maxLength: 20 });
const couponsArb = fc.array(couponArb, { maxLength: 5 });

These definitions compose four built-in Arbitrary functions to build the domain types.

  • fc.record: Generates an object by specifying an Arbitrary for each property
  • fc.constant: Returns the specified constant
  • fc.oneof: Randomly picks one of several Arbitrary instances to generate from
  • fc.integer({ min, max }) / fc.string({ minLength, maxLength }): Generate numbers and strings within the valid business range

Because TypeScript's type inference applies, annotating with fc.Arbitrary<CartItem> lets you catch mismatched property names or types at compile time.

Constraining Generated Values

When writing a custom Arbitrary, you sometimes want to impose constraints such as "only positive even numbers" or "only unit prices that are multiples of 100." fast-check provides .filter(), which discards values after generation, and fc.pre(), which declares preconditions at the start of a property. However, discarding large numbers of values with these lowers generation efficiency, and the test may fail when not enough valid cases can be collected.

Whenever possible, prefer constructions that only produce valid values in the first place. For example, to create "items whose unit price is in 100-yen increments," the recommended approach is to use .map() to multiply an integer by 100.

const multiplesOf100ItemArb: fc.Arbitrary<CartItem> = fc
  .integer({ min: 1, max: 1_000 })
  .map((units) => ({
    id: "item",
    unitPrice: units * 100,
    quantity: 1,
  }));

Note

In fast-check v4, the default generation ranges were made stricter to catch edge cases more aggressively. For example, fc.date() includes Invalid Date by default, and object-related Arbitrary functions may generate objects without a prototype (equivalent to Object.create(null)). If your tests assume a prototype exists, or you only want valid Date values, you can control this with options such as fc.date({ noInvalidDate: true }) or fc.record(..., { noNullPrototype: true }).

Finding Bugs and Reproducing Failures

From here, we will run fast-check against a cart calculation function that actually contains bugs, and walk through detecting the bugs and then pinpointing the minimal counterexample through shrinking.

The following calculateCartTotalBuggy is a discount calculation that looks fine at first glance. After computing the subtotal, it applies the coupons in order. For percentage coupons, it rounds down the fractional part; for fixed coupons, it subtracts the amount as is.

src/cart.ts
export function calculateCartTotalBuggy(
  items: readonly CartItem[],
  coupons: readonly Coupon[],
): number {
  const subtotal = calculateSubtotal(items);
 
  return coupons.reduce((total, coupon) => {
    if (coupon.type === "percentage") {
      return Math.floor(total * (1 - coupon.percent / 100));
    }
    return total - coupon.amount;
  }, subtotal);
}

For example, applying a 10%-off coupon to a 1,000-yen item returns 900 yen, and applying a 100-yen-off coupon to a 500-yen item returns 400 yen. An example-based test that only lists typical values like these would likely pass without issue. However, this function hides two bugs.

Let's uncover both bugs with property-based testing. As the first property, we test the invariant that "the discounted total must always be at least 0 and no greater than the pre-discount subtotal."

fc.assert(
  fc.property(cartItemsArb, couponsArb, (items, coupons) => {
    const subtotal = calculateSubtotal(items);
    const total = calculateCartTotalBuggy(items, coupons);
 
    expect(total).toBeGreaterThanOrEqual(0);
    expect(total).toBeLessThanOrEqual(subtotal);
  }),
);

When you run this test as is, a failure is detected on the very first run, and an error report like the following is printed.

Property failed after 1 tests
{ seed: 1861612236, path: "0:1:0:0:2:1:1:1:1:1:1:1:1:1:1:1:1:1:2", endOnFailure: true }
Counterexample: [[],[{"type":"fixed","amount":1}]]
Shrunk 18 time(s)

The reported counterexample (Counterexample) is "an empty cart with a single 1-yen-off fixed coupon applied." With an input this simple, it is immediately obvious that the guard preventing the total from dropping below 0 yen is missing when subtracting fixed coupons.

Notice the Shrunk 18 time(s) at the end. The failing case first found by random generation was actually far more complex, but after a failure, fast-check automatically performs shrinking, trimming the input bit by bit to narrow it down to the minimal counterexample that reproduces the same failure.

To see what the original counterexample would look like without shrinking, run the same trial with endOnFailure: true passed as the second argument to fc.assert to disable shrinking. The complex counterexample that was first found is printed as is.

Property failed after 1 tests
{ seed: 1861612236, path: "0", endOnFailure: true }
Counterexample: [[],[{__proto__:null,"type":"fixed","amount":31639},{__proto__:null,"type":"fixed","amount":3847},{__proto__:null,"type":"percentage","percent":68},{__proto__:null,"type":"fixed","amount":42129},{__proto__:null,"type":"fixed","amount":12977}]]
Shrunk 0 time(s)

The first failing input contains as many as five coupons (31,639 yen off, 3,847 yen off, 68% off, 42,129 yen off, and 12,977 yen off). Without shrinking, you would have to spend extra effort isolating the cause: "Is it the combination of percentage and fixed discounts?" "Does it break when there are five coupons?" Because fast-check removed the four unnecessary coupons and reduced the fixed coupon amount to 1 over 18 shrinking steps, you can identify the cause right away.

The second bug is a subtler floating-point error. When the subtotal is a multiple of 100 and an integer percentage discount is applied, "discounted total + discount amount === subtotal" should always hold. Let's verify this using the multiplesOf100ItemArb we defined earlier with .map().

fc.assert(
  fc.property(
    multiplesOf100ItemArb,
    fc.integer({ min: 0, max: 100 }),
    (item, percent) => {
      const total = calculateCartTotalBuggy([item], [
        { type: "percentage", percent },
      ]);
      const expectedDiscount = (item.unitPrice / 100) * percent;
 
      expect(total + expectedDiscount).toBe(item.unitPrice);
    },
  ),
);

Running this prints the following error report.

Property failed after 12 tests
{ seed: 1860626919, path: "11:1:0:0:0:2", endOnFailure: true }
Counterexample: [{"id":"item","unitPrice":900,"quantity":1},54]
Shrunk 5 time(s)

The failure was detected on the 12th run, and after 5 shrinking steps, the counterexample "a 54% discount on a 900-yen item" was found. With JavaScript's IEEE 754 floating-point numbers, 1 - 54 / 100 evaluates to 0.45999999999999996, so 900 * (1 - 54 / 100) becomes 413.99999999999994. Rounding this down with Math.floor turns a total that should be 414 yen into 413 yen. This is a bug that does not reproduce with the typical values humans and AI agents tend to write, such as 10%, 20%, or 50% off.

With tests that rely on random generation, a natural concern is whether a case that failed in CI can be reproduced locally. fast-check controls its pseudo-random number generator deterministically with a seed, so by passing the { seed, path, endOnFailure } from the error output directly as the second argument to fc.assert, you can reproduce just the failing counterexample in a single run.

fc.assert(
  fc.property(
    multiplesOf100ItemArb,
    fc.integer({ min: 0, max: 100 }),
    (item, percent) => {
      const total = calculateCartTotalBuggy([item], [
        { type: "percentage", percent },
      ]);
      const expectedDiscount = (item.unitPrice / 100) * percent;
 
      expect(total + expectedDiscount).toBe(item.unitPrice);
    },
  ),
  { seed: 1860626919, path: "11:1:0:0:0:2", endOnFailure: true },
);

With this configuration, the test immediately fails with the same counterexample.

Property failed after 1 tests
{ seed: 1860626919, path: "11:1:0:0:0:2", endOnFailure: true }
Counterexample: [{"id":"item","unitPrice":900,"quantity":1},54]
Shrunk 0 time(s)

Fixing the Bugs and Locking In Regression Tests with examples

calculateCartTotal is the implementation with both bugs fixed. For percentage discounts, it multiplies integers first and then divides by 100 to avoid intermediate floating-point errors. For fixed discounts, it sets a lower bound with Math.max(0, ...).

src/cart.ts
export function calculateCartTotal(
  items: readonly CartItem[],
  coupons: readonly Coupon[],
): number {
  const subtotal = calculateSubtotal(items);
 
  return coupons.reduce((total, coupon) => {
    if (coupon.type === "percentage") {
      return Math.floor((total * (100 - coupon.percent)) / 100);
    }
    return Math.max(0, total - coupon.amount);
  }, subtotal);
}

To make sure a counterexample you have found does not come back with future changes, register it in the examples option of fc.assert. Inputs specified in examples are always run before any randomly generated inputs.

Note that each counterexample must be registered in the examples of the property that detected it. For example, if you register the 900 yen × 54% counterexample with the first property (at least 0 and no greater than the subtotal), the test still passes, because the 413 yen returned by the buggy implementation satisfies that condition.

fc.assert(
  fc.property(cartItemsArb, couponsArb, (items, coupons) => {
    const subtotal = calculateSubtotal(items);
    const total = calculateCartTotal(items, coupons);
 
    expect(Number.isInteger(total)).toBe(true);
    expect(total).toBeGreaterThanOrEqual(0);
    expect(total).toBeLessThanOrEqual(subtotal);
  }),
  { examples: [[[], [{ type: "fixed", amount: 1 }]]] },
);
 
fc.assert(
  fc.property(
    multiplesOf100ItemArb,
    fc.integer({ min: 0, max: 100 }),
    (item, percent) => {
      const total = calculateCartTotal([item], [
        { type: "percentage", percent },
      ]);
      const expectedDiscount = (item.unitPrice / 100) * percent;
 
      expect(total + expectedDiscount).toBe(item.unitPrice);
    },
  ),
  { examples: [[{ id: "item", unitPrice: 900, quantity: 1 }, 54]] },
);

The first property also adds a Number.isInteger check to confirm that the total is a whole number of yen. This way, you keep the strengths of random exploration while also keeping deterministic regression tests for known bugs within the same test cases.

Designing Properties in Practice

When adopting property-based testing, the first hurdle is often deciding "which properties should I write?" If you rewrite the same calculation logic as the implementation inside your test code, you end up carrying the implementation's bugs into the test as well.

To restate the specification without depending on implementation details, it helps in practice to look for patterns that fit from a set of well-known ones like the following. These property design patterns are also systematically organized in Scott Wlaschin's article "Choosing properties for property-based testing."

  • Invariant: Verify ranges, types, or constraints that the output always satisfies regardless of the input (e.g., the total is an integer that is at least 0 and no greater than the subtotal)
  • Order independence / Commutativity: Verify that changing the order of the input does not change the result (e.g., reversing the array of items in the cart gives the same total)
  • Monotonicity: Verify that when the input increases or decreases, the output moves in the same direction, or at least never moves the opposite way (e.g., adding an item with a positive price never decreases the total)
  • Idempotency: Verify that applying the same operation twice gives the same result as applying it once (e.g., sorting, string normalization, deduplication)
  • Round-trip: Verify that applying a transformation followed by its inverse gets you back the original value (e.g., JSON.parse(JSON.stringify(x)) or decode(encode(x)) for a custom format)
  • Oracle comparison (Oracle / Differential Testing): Verify that the output of an optimized or refactored implementation matches a simple reference implementation (the oracle) whose correctness is obvious

Adding order independence and monotonicity to the e-commerce cart example lets you verify the specification without duplicating the implementation logic, as shown below.

src/cart.test.ts
it("reordering the items in the cart does not change the total (order independence)", () => {
  fc.assert(
    fc.property(cartItemsArb, couponsArb, (items, coupons) => {
      const reversed = [...items].reverse();
 
      expect(calculateCartTotal(reversed, coupons)).toBe(
        calculateCartTotal(items, coupons),
      );
    }),
  );
});
 
it("adding an item never decreases the total (monotonicity)", () => {
  fc.assert(
    fc.property(
      cartItemsArb,
      cartItemArb,
      couponsArb,
      (items, extraItem, coupons) => {
        const before = calculateCartTotal(items, coupons);
        const after = calculateCartTotal([...items, extraItem], coupons);
 
        expect(after).toBeGreaterThanOrEqual(before);
      },
    ),
  );
});

For transformations such as parsers and serializers, the round-trip pattern is especially effective.

fc.assert(
  fc.property(fc.array(fc.tuple(fc.string(), fc.string())), (entries) => {
    const encoded = new URLSearchParams(entries).toString();
    const decoded = [...new URLSearchParams(encoded).entries()];
 
    expect(decoded).toEqual(entries);
  }),
);

As these examples show, a key strength of property-based testing is that even when you cannot compute "the concrete correct value," you can isolate and verify just "the relationships that must hold."

Note

fast-check goes beyond testing pure functions like the ones covered in this article. It also supports model-based testing (fc.commands / fc.modelRun), which applies random sequences of operations to a stateful system and compares it against a model, and fc.scheduler(), which deliberately reorders the completion of asynchronous operations to detect race conditions.

Integrating with Vitest

In projects that use Vitest, adding the official connector @fast-check/vitest lets you skip nesting fc.assert and fc.property. In addition, Vitest's beforeEach / afterEach hooks run automatically for each run of a property, and syntax such as test.skip.prop and it.prop works as you would expect.

npm install --save-dev @fast-check/vitest

Importing test and fc from @fast-check/vitest instead of using test from vitest gives you access to test.prop. You can pass Arbitrary instances using either array syntax or object (record) syntax.

src/cart.vitest.test.ts
import { fc, test } from "@fast-check/vitest";
import { describe, expect } from "vitest";
import {
  calculateCartTotal,
  calculateSubtotal,
  type CartItem,
  type Coupon,
} from "./cart.js";
 
const cartItemArb: fc.Arbitrary<CartItem> = fc.record({
  id: fc.string({ minLength: 1, maxLength: 12 }),
  unitPrice: fc.integer({ min: 1, max: 100_000 }),
  quantity: fc.integer({ min: 1, max: 50 }),
});
 
const couponArb: fc.Arbitrary<Coupon> = fc.oneof(
  fc.record({
    type: fc.constant("percentage" as const),
    percent: fc.integer({ min: 0, max: 100 }),
  }),
  fc.record({
    type: fc.constant("fixed" as const),
    amount: fc.integer({ min: 0, max: 50_000 }),
  }),
);
 
describe("integration with @fast-check/vitest", () => {
  test.prop([
    fc.array(cartItemArb, { maxLength: 20 }),
    fc.array(couponArb, { maxLength: 5 }),
  ])("the total is at least 0 and no greater than the subtotal", (items, coupons) => {
    const subtotal = calculateSubtotal(items);
    const total = calculateCartTotal(items, coupons);
 
    expect(total).toBeGreaterThanOrEqual(0);
    expect(total).toBeLessThanOrEqual(subtotal);
  });
 
  test.prop(
    {
      items: fc.array(cartItemArb, { maxLength: 20 }),
      percent: fc.constant(100),
    },
    { numRuns: 200 },
  )("applying a 100% discount coupon always brings the total to 0", ({ items, percent }) => {
    const total = calculateCartTotal(items, [{ type: "percentage", percent }]);
    expect(total).toBe(0);
  });
});

The second argument of test.prop accepts parameters that control the number of runs and reproduction. The most commonly used options are:

  • numRuns: The number of random inputs to generate and run (defaults to 100)
  • examples: An array of fixed inputs that always run before random generation
  • seed: The initial seed for the pseudo-random number generator. Passing the same seed reproduces the same sequence of inputs
  • path: The exploration path printed in the failure report. Combined with seed, it lets you rerun a specific counterexample directly
  • endOnFailure: When true, stops immediately at the first failure without shrinking

Summary

  • In development where AI agents generate implementations and tests together, example-based tests that only check concrete representative values tend to inherit the same blind spots as the implementation. This makes property-based testing, which verifies the properties code must satisfy using automatically generated data, increasingly important
  • Property-based testing consists of three elements: the Arbitrary, which handles input generation and shrinking; the Property, which describes what must hold; and Shrinking, which narrows a failure down to the minimal counterexample
  • In fast-check, you can define type-safe custom Arbitrary instances by combining fc.record, fc.oneof, and fc.array. For constrained data, generating only valid values from the start with a constrained Arbitrary or .map() is more efficient than filtering values out with .filter()
  • The Counterexample printed on failure is minimized by shrinking, and specifying seed and path reproduces it deterministically in a single run. Counterexamples you find can be added to the examples option and locked in as regression tests
  • When deciding which properties to write, the key is to restate the specification without depending on implementation details. It helps to look for a fit among well-known patterns: invariants, order independence, monotonicity, idempotency, round-trips, and oracle comparison
  • With @fast-check/vitest, you can use test.prop / it.prop while keeping Vitest's test / it syntax, and beforeEach / afterEach hooks run automatically for each run

References

Comprehension check

Answer the following questions to deepen your understanding of the article.

What is the role of shrinking when fast-check detects a test failure?

  • It automatically reduces the number of random runs to shorten test time

    Try again

    The number of runs is controlled by the numRuns option. Shrinking is the process of simplifying a counterexample after a failure.

  • It removes unnecessary parts of a randomly generated counterexample and narrows it down to the minimal counterexample that still reproduces the failure

    Correct!

    As explained in the article, shrinking strips unnecessary parts from a complex counterexample and narrows it down to a minimal one that makes the cause easy to identify.

  • It automatically skips failed test cases and continues with the remaining properties

    Try again

    Shrinking does not ignore failures. It simplifies the input as far as the failure can still be reproduced and reports the minimal counterexample.

  • It rewrites the assertions in your test code so the test passes on the next run

    Try again

    Shrinking never changes your test code. It only shrinks the input values generated by the framework, step by step.

When generating test data that must satisfy specific constraints, why does the article recommend constrained Arbitraries or .map() over .filter()?

  • Because using .filter() makes TypeScript infer every type as unknown

    Try again

    The reason given in the article is generation efficiency, not type inference. The problem is that discarding many values can prevent enough valid cases from being collected.

  • Because .filter() was removed in fast-check v4 and throws at runtime

    Try again

    .filter() is still available, but the article explains that discarding large numbers of values should be avoided because it lowers efficiency and can cause failures.

  • Because discarding many values with .filter() lowers generation efficiency, and the test may fail when not enough valid cases can be collected

    Correct!

    As the article explains, generating only valid values from the start with a constrained Arbitrary or .map() is more efficient than filtering values out after generation.

  • Because .map() disables random generation and always returns a fixed value

    Try again

    .map() transforms the random values generated by the source Arbitrary and keeps its shrinking behavior intact.

Which fast-check option should you use to make sure a counterexample you found is always checked before random generation, even after future changes?

  • examples

    Correct!

    As explained in the article, counterexamples registered in examples are always run before any randomly generated inputs, locking them in as regression tests.

  • endOnFailure

    Try again

    When set to true, endOnFailure stops at the first failure without shrinking. It does not register fixed inputs.

  • numRuns

    Try again

    numRuns specifies how many random inputs are generated and run (100 by default).

  • noNullPrototype

    Try again

    noNullPrototype is an option for Arbitraries such as fc.record that prevents them from generating objects without a prototype.

Among the property design patterns introduced in the article, which one describes the property "adding an item with a positive price to the cart never decreases the total"?

  • Idempotency

    Try again

    Idempotency means applying the same operation twice gives the same result as applying it once, as with sorting.

  • Round-trip

    Try again

    Round-trip means applying a transformation followed by its inverse, such as encoding and decoding, gets you back the original value.

  • Order independence / Commutativity

    Try again

    Order independence means reordering the items in the cart does not change the total.

  • Monotonicity

    Correct!

    As explained in the article, monotonicity is the property that when the input increases or decreases, the output moves in the same direction, or at least never moves the opposite way.