For AI agents: the documentation index is at /llms.txt. Markdown versions of pages are available by appending .md to the URL.
Skip to main content

Testing

Introduction​

Envio ships with a built-in testing library that doubles as a development loop. createTestIndexer() runs your real handlers in-process, so you can iterate on logic and validate behavior without deploying anywhere. It's designed for:

  • TDD: Write a failing test, implement the handler, capture the snapshot, commit
  • Unit tests: Feed synthetic events directly into handlers to exercise edge cases in isolation
  • E2E tests against real blockchain data: Pin a block range or let the indexer auto-detect the first block with events, and run your full handler pipeline end-to-end
  • Regression-proof assertions: Inspect entities and per-block change sets, then lock in expected output with toMatchInlineSnapshot

The library integrates well with Vitest (recommended) and any other JavaScript-based testing framework.

Getting Started​

The simplest way to start is auto-exit mode - no block ranges, no mock events. The indexer automatically finds the first block with events and processes it.

import { describe, it } from "vitest";
import { createTestIndexer } from "envio";

describe("Indexer Testing", () => {
it("Should process first two blocks with events", async (t) => {
const indexer = createTestIndexer();

t.expect(
await indexer.process({ chains: { 1: {} } }),
"Should find the first block with an event on chain 1 and process it."
).toMatchInlineSnapshot();

t.expect(
await indexer.process({ chains: { 1: {} } }),
"Should find the second block with an event on chain 1 and process it."
).toMatchInlineSnapshot();
});
});

Run pnpm test - Vitest auto-fills the snapshots on first run. Review and commit them.

Auto-exit mode and explicit block ranges fetch real blocks from the chain's data source: its HyperSync endpoint, which needs ENVIO_API_TOKEN set (for example in your project's .env), or its for: sync RPC. Tests that only use simulate run offline without it.

A real-data test can take longer than the template's default 20 second timeout. If it times out, raise the timeout for that test, for example it("...", { timeout: 120_000 }, async (t) => { ... }). Failed source requests are retried and the indexer logs nothing by default (the HyperSync client may still print connection errors), so a bad RPC or token also shows up as a timeout: rerun with LOG_LEVEL=warn to see the error.


Process API​

indexer.process({ chains }) is the single entry point for driving the indexer. The shape of each chain entry determines the mode.

Processes the first block with matching events for each chain, then exits. Each subsequent call continues from where the previous one stopped.

const result = await indexer.process({
chains: {
1: {}, // auto-detect first block with events on chain 1
100: {}, // same for chain 100
},
});

Explicit block range​

Process a specific block range. Use when you need deterministic, pinned snapshots.

const result = await indexer.process({
chains: {
1: { startBlock: 10_861_674, endBlock: 10_861_766 },
},
});

startBlock and endBlock are both inclusive (unlike HyperSync's exclusive to_block). process() waits until the chain reaches endBlock, so on a local Hardhat or Anvil chain keep endBlock at or below the head, or the test times out.

A test indexer only moves forward. startBlock defaults to the chain's configured start block, or to one past the last block a previous call processed. It throws if startBlock is below the configured start block or not past the previous call's progress, and if endBlock is above the configured end_block. After a simulate call, that progress is the last block the call processed something at, usually its last item's block, not the endBlock you passed. To go back, create a new indexer with createTestIndexer().

Simulate (mock events)​

Feed synthetic events instead of fetching them from HyperSync or RPC. Best for unit-testing handler logic. Effects your handlers call still run for real, see Effects in Tests.

import { TestHelpers } from "envio";

const [addr1, addr2] = TestHelpers.Addresses.mockAddresses;

await indexer.process({
chains: {
1: {
simulate: [
{
contract: "ERC20",
event: "Transfer",
params: { from: addr1, to: addr2, value: 100n },
},
],
},
},
});

TestHelpers.Addresses.mockAddresses is a fixed tuple of 20 checksummed test addresses, and TestHelpers.Addresses.defaultAddress is the first of them.

You can pass multiple events in a single simulate array. You can optionally override event metadata per item using the same block / transaction / srcAddress / logIndex shape that real events expose. See field_selection for the full list of overridable fields.

block and transaction overrides are typed from config.yaml

The override types come from field_selection in config.yaml, not from a handler's fields option. If you select a field only with fields, setting it in simulate is a type error (FieldNotSelected<...>), even though the value still reaches the handler at runtime. block.timestamp and block.hash are always in the config selection, so overriding them type-checks. For other fields, either also list the field under the event's field_selection and rerun envio codegen:

events:
- event: Transfer(address indexed from, address indexed to, uint256 value)
field_selection:
transaction_fields:
- hash

or cast the override, for example transaction: { hash: "0xabc" } as any.

Defaults and ordering​

  • Items run in block order, then logIndex order, just like in production, whatever their order in the array.
  • An item without block.number takes the previous item's block number, starting at the call's startBlock.
  • On Fuel, blocks have id, height and time, so set block: { height } instead of number.
  • logIndex counts up from 0 across the whole call, not per block, and continues after any explicit logIndex: { logIndex: 12 } followed by an item without one gives 12, then 13. Two items can't share both a block number and a logIndex.
  • Block and transaction fields you don't set take zero values: block.timestamp is 0 and hashes are "". Omitted params do too: 0n, the zero address, false, "" or []. Set transaction.hash if your ids are built from it, or every id like `${event.transaction.hash}-${event.logIndex}` starts with -.
  • srcAddress defaults to the contract's first configured address on that chain, or the zero address for a wildcard event or a contract with no configured address.
  • srcAddress is converted to your address_format, but addresses in params reach the handler exactly as you write them. mockAddresses are checksummed, so with address_format: lowercase, lowercase them yourself (mockAddresses.map((a) => a.toLowerCase())) to match real events.
  • Without endBlock, the call ends at the highest block.number among its items, or at its startBlock if none sets one.

Items that never reach a handler​

Simulated items are routed like real logs. An item reaches no handler if its srcAddress isn't indexed for the contract (unless the event is a wildcard), if a where filter excludes it, or if its block is outside the call's startBlock-endBlock range. If any item reaches no handler, process() rejects with simulate: N item(s) you passed to simulate never reached a handler. To test that a filter excludes an event, assert the rejection:

// The handler only indexes mints: where: { params: { from: ZERO_ADDRESS } }
await t.expect(
indexer.process({
chains: {
1: {
simulate: [
{ contract: "ERC20", event: "Transfer", params: { from: addr1, to: addr2, value: 1n } },
],
},
},
}),
).rejects.toThrow("never reached a handler");

Block handlers​

Block handlers run in simulate too, on every block of the call's range their where matches. To give a block the fields a block handler selects with fields, add the block as its own item, with no contract or event:

await indexer.process({
chains: {
1: {
startBlock: 20_000_000,
endBlock: 20_000_200,
simulate: [{ block: { number: 20_000_100, timestamp: 1_717_001_200 } }],
},
},
});

Give each block number at most one block-only item. A block without one uses the block of the first event item at that number, or the zero-value defaults.

Transaction handlers​

On EVM chains, simulate also takes transactions as { transaction, block } items, which run your transaction handlers. Their defaults differ from simulated events, so see testing transaction handlers.

Dynamic contracts​

To test a factory, simulate the factory event first, then the child contract's event with srcAddress set to the address the contractRegister handler added. The child contract usually has no configured address, so without srcAddress its event gets the zero address and never reaches a handler. Both items can be in the same simulate array or in separate process() calls, and in the same block, except block 0. Items without a block.number start at the chain's start_block, so with start_block: 0 put the child in a later block, as below:

const [token0, token1, pool, trader] = TestHelpers.Addresses.mockAddresses;

const result = await indexer.process({
chains: {
1: {
simulate: [
{
// srcAddress defaults to the configured UniswapV3Factory address
contract: "UniswapV3Factory",
event: "PoolCreated",
params: { token0, token1, fee: 3000n, tickSpacing: 60n, pool },
},
{
contract: "UniswapV3Pool",
event: "Swap",
srcAddress: pool, // registered by the PoolCreated contractRegister handler
block: { number: 1 }, // later than PoolCreated's block 0
params: { sender: trader, recipient: trader, amount0: -1000n, amount1: 2000n },
},
],
},
},
});

t.expect(result.changes[0]?.addresses?.sets).toEqual([
{ address: pool, contract: "UniswapV3Pool" },
]);
t.expect(indexer.chains[1].UniswapV3Pool.addresses).toContain(pool);

result.changes​

result.changes is an array of per-block change objects. Each entry has block, chainId, eventsProcessed (which also counts block handler runs), plus entity names as keys with a sets array of created/updated entities and a deleted array of removed ids. Dynamic contract registrations appear under addresses.sets, one { address, contract } object per registered address.

Rules​

  • Only one process() call can run at a time on an indexer. Await each one.
  • Chains in one call run one after another, in chain id order.
  • Each createTestIndexer() has its own entity store. Within one indexer, entities and block progress carry over from one process() call to the next.
  • Module-level state in your handler files, such as a top-level let, is shared by every test indexer in the file. Reset it yourself if a test depends on it.
  • Reorg rollbacks are off in the test indexer.

Entity State API​

Preset state before processing and read entities after.

// Preset state before processing
indexer.EntityName.set({ id: "...", field: value, chainId: 1 }); // chainId only for per-chain entities

// Read state after processing
await indexer.EntityName.get("id"); // returns entity | undefined
await indexer.EntityName.getOrThrow("id"); // throws if not found
await indexer.EntityName.getAll(); // returns all entities of this type
await indexer.EntityName.getWhere({ owner_id: { _eq: "0x..." } }); // same filters as in handlers

These calls fail while a process() call is running: set throws, and the reads return a rejected promise. Await process() first.

The test indexer also exposes indexer.chainIds and indexer.chains, with the same shape as on the real indexer.

Per-chain entities need a chainId

With disable_default_cross_chain: true there is no chain in context outside a handler, so these chain-agnostic operations take one:

indexer.Counter.set({ id: "1", count: 0n, chainId: 1 });

// Rejects if the id exists on more than one chain
await indexer.Counter.get("1");

// Narrow it instead
await indexer.Counter.getWhere({ chainId: { _eq: 1 } });

Entities read back this way include their chainId, for example { id: "1", count: 0n, chainId: 1 }, so add it to objects you compare with toEqual, or use toMatchObject. Entities in result.changes don't carry it; the change entry's own chainId says which chain they're on.


Effects in Tests​

The test indexer runs your effects for real, in simulate too, so an effect that calls an RPC or an API makes that request during the test. It doesn't keep effect results between process() calls either, so cache: true doesn't stop an effect from running again.

There is no API to mock an effect, and vi.mock() doesn't reach your handler files or the modules they import: the test indexer loads them with Node's own import, outside Vitest's module graph. To keep a unit test offline:

  • If your handler only calls the effect when an entity is missing (for example, token metadata it stores once), pre-seed that entity with indexer.Token.set({ ... }) before indexer.process(), so the handler skips the call.
  • Or make the endpoint configurable and point it at a stub server your test starts. Read the URL inside the effect function: handler files are imported once per test process, so a client created at module level keeps the URL it was first created with.
// src/effects/getTokenPrice.ts
import { createEffect, S } from "envio";

export const getTokenPrice = createEffect(
{ name: "getTokenPrice", input: S.string, output: S.number, rateLimit: false, cache: true },
async ({ input }) => {
const baseUrl = process.env.PRICE_API_URL ?? "https://api.example.com";
const response = await fetch(`${baseUrl}/price/${input}`);
const { price } = (await response.json()) as { price: number };
return price;
},
);
// In the test
process.env.PRICE_API_URL = stubServerUrl; // e.g. a node:http server listening on localhost
const indexer = createTestIndexer();

Assertions​

The testing library works with any JavaScript assertion library. The examples below use t.expect, the expect from Vitest's test context.

// Snapshot (recommended, captures full output, auto-filled on first run)
t.expect(result.changes).toMatchInlineSnapshot();

// Entity assertions
const pool = await indexer.Pool.getOrThrow(poolId);
t.expect(pool).toEqual({ id: poolId, token0_id: "0xabc..." });

// Count
t.expect(result.changes[0]?.Pair?.sets).toHaveLength(1);

// Contract addresses (after dynamic registration)
t.expect(indexer.chains[1].MyContract.addresses).toContain("0x1234...");

TDD Workflow​

  1. Write a failing test with expected entity output
  2. Implement the handler until the test passes
  3. Capture the snapshot - run pnpm test to fill toMatchInlineSnapshot
  4. Review and commit the snapshot for regression testing
Warning

Do not add tests which simply restate the implementation. These provide zero confidence.

Running Tests​

pnpm test              # Run all tests
pnpm test -u # Update snapshots
LOG_LEVEL=debug pnpm test # Also print logs, including context.log