Cookbook: Testing with Vitest
With Tevm, every Vitest test file — or even every individual test() block — can spin up its own native EVM chain in milliseconds with zero shared ports or daemon orchestration.
Setup
pnpm add tevm viem
pnpm add -D vitestPattern 1: Isolated client per test (recommended)
Create a small factory helper that tracks every client opened during a test and closes them all in afterEach:
import { createMemoryClient, type MemoryClient, parseEther, PREFUNDED_ACCOUNTS } from 'tevm'
import { afterEach, describe, expect, test } from 'vitest'
const clients: MemoryClient[] = []
const createClient = (options?: Parameters<typeof createMemoryClient>[0]) => {
const client = createMemoryClient(options)
clients.push(client)
return client
}
afterEach(async () => {
await Promise.all(clients.splice(0).map((c) => c.tevmClose()))
})
describe('ETH transfers', () => {
test('mines a queued transfer and updates balances', async () => {
const client = createClient({ mining: { auto: false } })
const alice = PREFUNDED_ACCOUNTS[0].address
const bob = '0x1111111111111111111111111111111111111111'
const { txHash } = await client.tevmCall({
from: alice,
to: bob,
value: parseEther('1'),
addToMempool: true,
})
// Still pending before mining
expect(txHash).toBeDefined()
expect(await client.getBalance({ address: bob })).toBe(0n)
await client.tevmMine({ blocks: 1 })
const receipt = await client.getTransactionReceipt({ hash: txHash! })
expect(receipt.status).toBe('success')
expect(await client.getBalance({ address: bob })).toBe(parseEther('1'))
})
})Pattern 2: Deploy, write, and read a contract
Use SimpleContract (or any contract imported via the Tevm Bundler):
import { createMemoryClient, PREFUNDED_ACCOUNTS } from 'tevm'
import { SimpleContract } from 'tevm/contract'
import { expect, test } from 'vitest'
test('deploys and updates SimpleContract', async () => {
const client = createMemoryClient({ account: PREFUNDED_ACCOUNTS[0] })
try {
const deployHash = await client.deployContract(SimpleContract.deploy(7n))
const receipt = await client.getTransactionReceipt({ hash: deployHash })
const contract = SimpleContract.withAddress(receipt.contractAddress!)
expect(await client.readContract(contract.read.get())).toBe(7n)
await client.writeContract(contract.write.set(42n))
expect(await client.readContract(contract.read.get())).toBe(42n)
} finally {
await client.tevmClose()
}
})Pattern 3: Reuse expensive setup with snapshots
When setup deploys a full protocol (or forks mainnet), take a snapshot once in beforeAll / beforeEach and revert in afterEach:
import { createMemoryClient } from 'tevm'
import { afterAll, afterEach, beforeEach, describe, expect, test } from 'vitest'
describe('snapshot isolation', () => {
const client = createMemoryClient()
const account = '0x3333333333333333333333333333333333333333'
let snapshotId: `0x${string}`
beforeEach(async () => {
snapshotId = await client.snapshot()
})
afterEach(async () => {
await client.revert({ id: snapshotId })
})
afterAll(async () => {
await client.tevmClose()
})
test('mutates balance without leaking', async () => {
await client.setBalance({ address: account, value: 100n })
expect(await client.getBalance({ address: account })).toBe(100n)
})
test('starts back at zero', async () => {
expect(await client.getBalance({ address: account })).toBe(0n)
})
})Pattern 4: Time travel and hardfork activation
Local genesis starts at timestamp 0. Jump forward deterministically to test timelocks, vesting schedules, or timestamp-gated EIPs (like mainnet Osaka at 1764798551):
import { createMemoryClient } from 'tevm'
import { expect, test } from 'vitest'
test('advances next block timestamp', async () => {
const client = createMemoryClient()
try {
const targetTimestamp = 2_000_000_000n
await client.setNextBlockTimestamp({ timestamp: targetTimestamp })
await client.mine({ blocks: 1 })
const block = await client.getBlock({ blockTag: 'latest' })
expect(block.timestamp).toBe(targetTimestamp)
} finally {
await client.tevmClose()
}
})Pattern 5: Assert revert bytes and opcode traces
Check exact custom error selectors or inspect a reverting call with debug_traceCall:
import { createMemoryClient, NativeRpcError } from 'tevm'
import { expect, test } from 'vitest'
test('captures revert data and opcode trace', async () => {
const client = createMemoryClient()
try {
const target = '0x4444444444444444444444444444444444444444'
await client.tevmSetAccount({
address: target,
deployedBytecode: '0x63deadbeef6000526004601cfd',
})
await expect(client.tevmCall({ to: target })).rejects.toMatchObject({
code: 3,
data: '0xdeadbeef',
})
const trace = (await client.transport.tevm.request({
method: 'debug_traceCall',
params: [{ to: target }, 'latest', { enableReturnData: true }],
})) as { failed: boolean; returnValue: string; structLogs: Array<{ op: string }> }
expect(trace.failed).toBe(true)
expect(trace.returnValue).toBe('0xdeadbeef')
expect(trace.structLogs.at(-1)?.op).toBe('REVERT')
} finally {
await client.tevmClose()
}
})Next: Forking mainnet cookbook · Viem cookbook · Tracing & engine events

