Hegel is a property-based testing library for TypeScript, built on libhegel,
the Hegel engine: a native library on Node, Bun and
Deno, and the same engine compiled to WebAssembly in browsers.
Getting started
This guide walks you through the basics of installing Hegel and writing your
first tests.
Install Hegel
Add @hegeldev/hegel to your project as a dev dependency:
npminstall--save-dev@hegeldev/hegel
Hegel supports Node 20.11+, Bun 1.2.5+, Deno 2+, and modern ESM browsers.
Browser module loading initializes Wasm with top-level await.
Write your first test
You're now ready to write your first test. We'll use
Vitest as the test runner for the purposes of this
guide. Create a new test file:
import { test } from"vitest"; import*ashegelfrom"@hegeldev/hegel"; import*asgsfrom"@hegeldev/hegel/generators";
test("integer self equality", () => hegel.test((tc) => { constn = tc.draw(gs.integers()); if (n !== n) { thrownewError("integer was not equal to itself"); } }));
Now run the test using npx vitest run. You should see that this test
passes.
Let's look at what's happening in more detail. test runs your test
many times (100, by default). The test function receives a TestCase,
which provides a draw method for drawing different
values. This test draws a random integer and checks that it should be equal
to itself.
Next, try a test that fails:
test("integers always below 50", () => hegel.test((tc) => { constn = tc.draw(gs.integers()); if (n >= 50) { thrownewError(`n=${n} is too large`); } }));
This test asserts that any integer is less than 50, which is obviously
incorrect. Hegel will find a test case that makes this assertion fail, and
then shrink it to find the smallest counterexample — in this case, n = 50.
To fix this test, you can constrain the integers you generate with the
minValue and maxValue options:
test("bounded integers always below 50", () => hegel.test((tc) => { constn = tc.draw(gs.integers({ minValue:0, maxValue:49 })); if (n >= 50) { thrownewError(`n=${n} is too large`); } }));
Run the test again. It should now pass.
Use generators
Hegel provides a rich library of generators that you can use out of the box.
There are primitive generators, such as integers, floats, and text,
and combinators that allow you to make generators out of other generators,
such as arrays and maps.
For example, you can use arrays to generate an array of integers:
test("append increases length", () => hegel.test((tc) => { constxs = tc.draw(gs.arrays(gs.integers())); constinitialLength = xs.length; xs.push(tc.draw(gs.integers())); if (xs.length <= initialLength) { thrownewError("length did not increase"); } }));
This test checks that appending an element to a random array of integers
should always increase its length.
You can also build composite values out of multiple generators. The simplest
way is to draw fields directly inside the test body:
interfacePerson { age: number; name: string; }
test("person", () => hegel.test((tc) => { constperson: Person = { age:tc.draw(gs.integers({ minValue:0, maxValue:120 })), name:tc.draw(gs.text({ minSize:1, maxSize:50 })), }; // use person in your test voidperson; }));
For composite values you want to reuse across tests, build a generator with
composite (imperative — call tc.draw() on inner generators inside a
builder function) or record (declarative — pass a schema mapping field
names to generators). Both produce a generator that supports .map(),
.filter(), and .flatMap() like any other generator.
Note that you can feed the results of one draw into subsequent calls — this
is what composite is for. For example, say that you extend the Person
interface to include a drivingLicense boolean field, where the field
depends on age:
For recursive data, such as trees or JSON documents, use
gs.recursive: give it the generator of leaves, and a function that builds
one level of structure from a generator of sub-values. The engine decides
where values branch and keeps them within maxDepth and maxLeaves; use
gs.deferred for definitions that refer to each other.
test("addition is commutative", () => hegel.test((tc) => { constx = tc.draw(gs.integers()); consty = tc.draw(gs.integers()); tc.note(`x + y = ${x+y}, y + x = ${y+x}`); if (x + y !== y + x) { thrownewError("addition is not commutative"); } }));
When a test fails, Hegel prints the smallest failing example it found:
each drawn value as a line of JavaScript, in the order drawn, with the
notes between them, then the line to replay it with. For a test like the
one above, that looks like:
const draw_1 = 0;
const draw_2 = -1;
x + y = -1, y + x = -1
To reproduce this failure, replay it with the Hegel builder:
.reproduceFailure("AXicY2BgYGQAAAAJAAI")
Pass a name to draw to print a value under it (tc.draw(gs.integers(), "x") prints const x_1 = ...;, a second draw under the name const x_2 = ...;), and use drawSilent for a value not worth printing. Notes and drawn values are
only printed for the failing example (and for every test case of a
verbose run), so they cost nothing while Hegel searches.
Each value is printed by the generator that drew it, as it draws it, so
draw takes a generators.PrintableGenerator: every built-in
generator is one whenever the generators it is built from are. Give a
generator a printed form of your own with
printWith, and see
PrettyPrinter for the printer it writes to.
newhegel.Hegel((tc) => { constx = tc.draw(gs.integers()); consty = tc.draw(gs.integers()); // ... }) .example(0, -1) .reproduceFailure("AXicY2BgYGQAAAAJAAI") // the blob printed by the failure .runSync();
Guide the search
target steers generation toward test cases that
maximise a score, event and
eventValue record what happened (reported with
the showStatistics setting), and repeat runs a
workload an engine-chosen number of times, shrinking the number of
repetitions along with what each drew. For concurrent code, give each task
its own clone of the test case, so that what one
draws does not depend on how the tasks interleave.
Change the number of test cases
By default Hegel runs 100 test cases. To override this, pass a
Settings override as the second argument to test:
test("integers many", () => hegel.test( (tc) => { constn = tc.draw(gs.integers()); if (n !== n) { thrownewError("integer was not equal to itself"); } }, { testCases:500 }, ));
Settings you leave out keep the values the engine resolves from the
settings profile: development locally, ci on a CI server (derandomized,
with the database off) and workload inside Antithesis, with hegel.toml
and the HEGEL_* environment variables applied over it. Register your own
profiles with registerProfile and select one with the profile
setting or setDefaultProfile:
A test resolves the profile when it runs. To resolve it once, ahead of the
tests, resolveSettings returns every setting as the engine resolves
it now, as a plain object to pass to test or spread into another:
Hegel configures a test with builder methods instead, including the
key its failures are saved under (by default its file and name) and its
location for Antithesis (by default where it was defined).
Understand what a run throws
A failing test throws its own error, from the smallest failing example, so
assertion libraries show their usual diff; with
reportMultipleFailures, several distinct failures are thrown together as
an AggregateError. A run the engine aborts throws a RunError: a
FailedHealthCheckError, FlakyError or
UnsatisfiableError, or a plain RunError for anything else. A run
replaying failure blobs none of which fails any more throws a
DidNotReproduceError.
Test stateful systems
Some bugs only show up after a particular sequence of operations. For
those, describe the operations as the rules of a state machine and let
Hegel search over sequences of them — see the stateful module:
Hegel is a property-based testing library for TypeScript, built on libhegel, the Hegel engine: a native library on Node, Bun and Deno, and the same engine compiled to WebAssembly in browsers.
Getting started
This guide walks you through the basics of installing Hegel and writing your first tests.
Install Hegel
Add
@hegeldev/hegelto your project as a dev dependency:Hegel supports Node 20.11+, Bun 1.2.5+, Deno 2+, and modern ESM browsers. Browser module loading initializes Wasm with top-level await.
Write your first test
You're now ready to write your first test. We'll use Vitest as the test runner for the purposes of this guide. Create a new test file:
Now run the test using
npx vitest run. You should see that this test passes.Let's look at what's happening in more detail. test runs your test many times (100, by default). The test function receives a TestCase, which provides a draw method for drawing different values. This test draws a random integer and checks that it should be equal to itself.
Next, try a test that fails:
This test asserts that any integer is less than 50, which is obviously incorrect. Hegel will find a test case that makes this assertion fail, and then shrink it to find the smallest counterexample — in this case,
n = 50.To fix this test, you can constrain the integers you generate with the
minValueandmaxValueoptions:Run the test again. It should now pass.
Use generators
Hegel provides a rich library of generators that you can use out of the box. There are primitive generators, such as
integers,floats, andtext, and combinators that allow you to make generators out of other generators, such asarraysandmaps.For example, you can use
arraysto generate an array of integers:This test checks that appending an element to a random array of integers should always increase its length.
You can also build composite values out of multiple generators. The simplest way is to draw fields directly inside the test body:
For composite values you want to reuse across tests, build a generator with
composite(imperative — calltc.draw()on inner generators inside a builder function) orrecord(declarative — pass a schema mapping field names to generators). Both produce a generator that supports.map(),.filter(), and.flatMap()like any other generator.Note that you can feed the results of one
drawinto subsequent calls — this is whatcompositeis for. For example, say that you extend thePersoninterface to include adrivingLicenseboolean field, where the field depends onage:For recursive data, such as trees or JSON documents, use
gs.recursive: give it the generator of leaves, and a function that builds one level of structure from a generator of sub-values. The engine decides where values branch and keeps them withinmaxDepthandmaxLeaves; usegs.deferredfor definitions that refer to each other.Debug your failing test cases
Use the note method to attach debug information:
When a test fails, Hegel prints the smallest failing example it found: each drawn value as a line of JavaScript, in the order drawn, with the notes between them, then the line to replay it with. For a test like the one above, that looks like:
Pass a name to
drawto print a value under it (tc.draw(gs.integers(), "x")printsconst x_1 = ...;, a second draw under the nameconst x_2 = ...;), and use drawSilent for a value not worth printing. Notes and drawn values are only printed for the failing example (and for every test case of a verbose run), so they cost nothing while Hegel searches.Each value is printed by the generator that drew it, as it draws it, so
drawtakes a generators.PrintableGenerator: every built-in generator is one whenever the generators it is built from are. Give a generator a printed form of your own with printWith, and see PrettyPrinter for the printer it writes to.To replay a failure, pass the blob to reproduceFailure; to always run some inputs first, give them as explicit examples:
Guide the search
target steers generation toward test cases that maximise a score, event and eventValue record what happened (reported with the
showStatisticssetting), and repeat runs a workload an engine-chosen number of times, shrinking the number of repetitions along with what each drew. For concurrent code, give each task its own clone of the test case, so that what one draws does not depend on how the tasks interleave.Change the number of test cases
By default Hegel runs 100 test cases. To override this, pass a Settings override as the second argument to test:
Settings you leave out keep the values the engine resolves from the settings profile:
developmentlocally,cion a CI server (derandomized, with the database off) andworkloadinside Antithesis, withhegel.tomland theHEGEL_*environment variables applied over it. Register your own profiles with registerProfile and select one with theprofilesetting or setDefaultProfile:A test resolves the profile when it runs. To resolve it once, ahead of the tests, resolveSettings returns every setting as the engine resolves it now, as a plain object to pass to test or spread into another:
Neither registerProfile nor setDefaultProfile changes settings resolved before it was called.
Hegel configures a test with builder methods instead, including the key its failures are saved under (by default its file and name) and its location for Antithesis (by default where it was defined).
Understand what a run throws
A failing test throws its own error, from the smallest failing example, so assertion libraries show their usual diff; with
reportMultipleFailures, several distinct failures are thrown together as anAggregateError. A run the engine aborts throws a RunError: a FailedHealthCheckError, FlakyError or UnsatisfiableError, or a plainRunErrorfor anything else. A run replaying failure blobs none of which fails any more throws a DidNotReproduceError.Test stateful systems
Some bugs only show up after a particular sequence of operations. For those, describe the operations as the rules of a state machine and let Hegel search over sequences of them — see the stateful module:
Learning more
@hegeldev/hegel/generatorsmodule for the full list of available generators.