Repository navigation
Releases
v0.3.0
This release better aligns mocks to do what they look like they should do. When you mock a contract's function, that mock answers the app's transactions to it, gas estimate included, instead of competing with a general mock.actions mock elsewhere in the setup. A mock that could never match now fails when you register it, instead of silently never answering. When something doesn't match, the error and the history say what the app asked for and which mocks came close.
It's a release with many breaking changes, but most are a rename or a stricter rule, and each one below says what to change. Two API removals that touch the most surface area have before-and-after examples.
⚠️ Breaking Changes
You're affected if your tests use .fails(name), a send resolver's emit() or revert(), action mocks for a contract's functions, match.any() or match.where() in a pin, a send's data, LogsCall, or mock.method() with a typed name. The rest refuse bad setups loudly at registration, or reword messages.
Who answers a transaction
-
Only a contract's mocks answer its functions. An estimate or a send of a registered contract's nonpayable or payable function is answered by that contract's
estimateGasandwritemocks and itsdefaults, never bymock.actions.estimateGas()ormock.actions.sendTransaction(). Move those mocks onto the contract:usdc.write.transfer()as the catch-all, andusdc.estimateGas.transfer().returns(n)to set the gas. In practice:- a shared
mock.actions.estimateGas().returns(n)no longer sets the gas for a contract's writes. A write mock also answers the estimate, with 100,000 gas, unless the contract has its ownestimateGasmock; - a blanket
mock.actions.estimateGas().refuses(…)no longer reaches a contract's functions. Put.refuses()on the contract's mock instead; - when the contract's mocks miss a send, the error is the contract's miss, and it lists the action mocks that would have matched.
assertAllUsed()reports an action mock left unused this way, and says why.
ETH sent to a contract with no data, a selector that isn't on its ABI, and an estimate of a view function are still answered by action mocks.
eth_callis unchanged. - a shared
-
A node's refusal by name is now
.refuses(name), not.fails(name). In a resolver, userefuse(name)instead offail(name). It's typed onsimulate,estimateGas, andwritemocks, and onmock.actions.estimateGas()andmock.actions.sendTransaction(), with the same names each took before..fails(),fail(), andfailRequests()now take only a fault (an HTTP error, a JSON-RPC error, a timeout, or a network failure). A name passed to them is a type error, and aMockSetupErrorat runtime. The app receives the same error as before.// 0.2.0 usdc.write.transfer().fails("insufficientFunds"); mock.actions.sendTransaction().fails("nonceTooLow"); let attempts = 0; usdc.write.approve().returns(({ fail }) => { if (++attempts === 1) fail("nonceTooLow"); }); // 0.3.0 usdc.write.transfer().refuses("insufficientFunds"); mock.actions.sendTransaction().refuses("nonceTooLow"); let attempts = 0; usdc.write.approve().returns(({ refuse }) => { if (++attempts === 1) refuse("nonceTooLow"); });
Beyond the method names:
- history records a refusal as
{ type: "refusal", name }, shown as✗ refused: nonceTooLow; - a request repeated after a refusal is no longer marked
(retry), because viem doesn't retry a refusal; MockNodeFaultis no longer exported.
- history records a refusal as
-
A send mock's resolver returns only what the chain did, so its
emit()andrevert()are gone. This covers a contract'swriteresolvers,defaults.writeresolvers, andmock.actions.sendTransaction()resolvers; a static.emits()is unchanged.revert()never reverted the call: the estimate passed, and the send was mined reverted. Return{ status: "reverted" }to get that outcome, and return the logs instead of emitting them:// 0.2.0 token.write.transfer().returns(({ from, args: [to, amount], emit, revert }) => { const have = balances.get(from) ?? 0n; if (have < amount) revert({ errorName: "ERC20InsufficientBalance", args: [from, have, amount] }); emit(token.events.Transfer({ from, to, value: amount })); balances.set(from, have - amount); balances.set(to, (balances.get(to) ?? 0n) + amount); }); // 0.3.0 token.write.transfer().returns(({ from, args: [to, amount] }) => { const have = balances.get(from) ?? 0n; if (have < amount) return { status: "reverted" }; balances.set(from, have - amount); balances.set(to, (balances.get(to) ?? 0n) + amount); return { logs: [token.events.Transfer({ from, to, value: amount })] }; });
To revert the call itself, estimate included, so that a local account's
writeContract()throws the decoded error before it sends anything, register a.reverts()mock pinned to the args that revert, beside the resolver. It's more specific than the resolver's mock, so it answers those calls and leaves the rest to the resolver: see Resolvers in the README. To decide from the test's state instead, use anestimateGasresolver, which keepsrevert(). Also:read,simulate, andestimateGasresolvers keeprevert();revert()used to throw, so a helper that called it now has to return its verdict, and the resolver returns that;WriteResolverContexttakes one type parameter, the function's args;- untyped code that still calls
emit()orrevert()gets aMockResolverErrorending "is not a function". A resolver that returns{ logs: null }is refused, as a static.returns({ logs: null })already was.
What a mock matches
-
No pin matches a value that the call leaves out. A mock that pins a field doesn't match a call without that field, whatever the pin:
match.any()needs a value, and amatch.where()predicate is never called withundefined. SosendTransaction({ to, gas: match.any() })means "a send that gives gas", where before it behaved as ifgaswere left out. To match a call with or without a field, leave the key out.nullis a value, so it does matchmatch.any(). To select the calls that leave a field out, use a predicate for the whole params:sendTransaction(match.where((call) => call.gas === undefined)). A contract'sfrompin already worked this way. Now an action's fields and a raw method's params do too. The call is what the mock decodes (BalanceCall,SendTransactionCall, …), not the args the app passed, and it fills in what a node would assume. So a block is always set (blockNumber, or a log range'sfromBlockandtoBlock), as are a send's or an estimate'svalueanddata, andmatch.any()matches them whether the app gave them or not. -
An explicit
undefinedin a pin means the key was left out.getBalance({ address, blockNumber: undefined })now matches any block, and no longer outranks a later mock that leaves the key out.match.where((v) => v === undefined)never matches (see above). -
A send's and an estimate's call always have
data,"0x"when the request has none, the same asvalueis sent as0n. SosendTransaction({ to, data: "0x" })pins a plain transfer, where before it never matched one. An estimate of a deploy hasto: null, as a send's call does. In types:SendTransactionCall.dataandEstimateGasCall.dataare a requiredHex;EstimateGasCall.toisAddress | null.
What a test may see change:
- a
match.where()atdatais called with"0x"for a plain transfer, so one that decodes calldata throws there; - a resolver that tests for a missing
data, or for an estimate's missingto, takes the other branch; { data: match.any() }matches every send;- exact assertions on a plain send's
.calls, its history line (data: 0x), or its record inmock.transactions(input: "0x") need the new field.
-
Which mock answers:
match.any()now counts toward a mock's rank, after exact values and predicates. A mock that pins a key withmatch.any()answers ahead of one that's otherwise as specific and leaves the key out, whichever was registered first. Before, the one registered last answered;- an empty list in args or params (
totalOf([[]]),getLogs({ topics: [] })) counts as an exact value, so its mock answers ahead of one withmatch.any()ormatch.where()in that place, whichever was registered first; - one
match.any()in place of all of an action's or a raw method's params counts as nothing, since it matches every call. A mock that pins any param answers ahead of it. It ties with{}or[]params, where it used to answer ahead of them, so the one registered last answers. It still answers ahead of a mock with no params, such asgetBalance().
-
A mock that could never match is refused at registration with a
MockSetupErrorthat names what's wrong. Before, it registered and never answered. That covers:- a contract mock's args that don't fit its function: the wrong count, a value of the wrong type (
"5"for auint256), a key that isn't one of the struct's fields, or args that aren't a list. A malformed address still throws viem'sInvalidAddressError, as it does wherever a mock takes an address; - an
undefinedin the middle of a list, wherematch.any()is what's needed; - a Jest or Vitest matcher passed as an action's whole params, such as
sendTransaction(expect.objectContaining({ to })).
- a contract mock's args that don't fit its function: the wrong count, a value of the wrong type (
-
A mock of an overloaded function picks its overload by how its args fit: by count, then by type. A struct with fields left out that fits several overloads is now refused as ambiguous. Before, it registered on the first overload.
Types and messages
- **
LogsCallis either a block ran...
v0.2.0
This release tightens how the mock checks what a test gives it. A value the mock can't use is refused where it's given, with a message that names the call and field (e.g. mock.addTransaction()'s gasUsed must be a non-negative bigint; got -1n.), instead of being ignored or turned into a plausible-looking answer. An explicit undefined now always means the same as leaving the key out, so spreading a partial fixture behaves as expected.
⚠️ Breaking Changes
MockEventLogis renamedMockLogContent. It's the type for any log's content,testLog()'s included, not only an event's.- A revert spec takes one form:
data,panic, orerrorNamewithargs. A spec with fields of two forms is a type error, and is refused at runtime. - A
defaults:entry set toundefinedregisters no mock. Before,read,simulateandwriteanswered zero for it. - Newly refused at registration:
- a count past
Number.MAX_SAFE_INTEGERintimes(),failRequests()'times,historyLimit,historyOnFailureorchain.blockTime; - a matcher (
match.any()and the rest) anywhere a value goes, such as a revert spec'sargs. Matchers go in a mock's args, params and pins; - a
failRequests()methodthat isn't a method name or a list of them, e.g. a regex; - a receipt's
statusthat isn't"success"or"reverted", e.g."0x1"copied from a node; - a field that isn't a fee in
createMockRpc({ fees })ormock.setFees(), e.g. themaxFeePerGasof aclient.estimateFeesPerGas()result; - a receipt mock with logs over a transaction that reverted.
- a count past
- Error classes: a negative balance, gas price, fee or fee history value is the mock's
MockSetupError, not viem'sIntegerOutOfRangeError. - Messages: most setup errors are reworded. Assert on the error class (
toThrow(MockSetupError)) or itscode, not its text.
Bug Fixes
- An
undefinedfield is left out everywhere: fees, revert specs, a mock's answer fields, and an unknown key holdingundefined. - A pending transaction can null only some of its block fields.
- An ABI function named after an
Object.prototypemember (toString,valueOf) can be mocked. - A bigint request param after a fault no longer crashes the request.
- Errors and warnings use the package's current name. The hint for an estimate or send nothing answers also mentions
.reverts().
👉 Changelog
🩹 Fixes
⚠️ Refuse a revert spec with fields of two forms (4a53ae7)- Point the reverted-receipt refusal at the record (
19e25ed) ⚠️ Register no default for a defaults entry that's undefined (5b2dc8f)- Refuse a receipt mock with logs over a reverted transaction (
caa0b0c) - Treat an explicit undefined in a mock's fields as left out (
d2c90c1) - Treat an undefined panic or data in a revert spec as left out (
5aa21ed) - Accept a pending transaction that nulls only some of its block fields (
06257b8) - Treat an undefined fee as left out in createMockRpc and setFees (
2304007) - Don't crash on bigint request params after a fault (
3cc82c8) - Mock ABI functions named after Object.prototype members (
c98f109) - Update package name in errors and warnings; add .reverts() to the estimate and send hint (
22ce5c5)
💅 Refactors
- Refuse placed logs in the log content check, and name each log's call (
0fbd443) - Hint at fixes for revert-arg matchers, left-out estimates and estimate-shaped fees, and let checkFields take a plain hint (
ddb0fb0) ⚠️ Rename MockEventLog to MockLogContent (f6bdc32)- Check hex, lists, and objects with helper functions (
1d94337) - Check fee history fields one-by-one with checkAmount, and word answer object checks alike (
b8ca1e6) - Note MockInternalError can also come from a value its types don't allow (
e78c7a6) - Drop typeof checks that isHex and isHash already make, and a dead branch (
706da38) - Refuse matchers in revert specs and failRequests' method, naming each place (
dc28e7a) - Check transaction status with one shared checkStatus (
aef5e57) - Check objects of known fields with one shared checkFields (
f2d1853) - Check counts with one shared checkCount, and word both helpers alike (
b5b5860) - Move mock.buildLog()'s placement out of logs/events.ts (
e45b449) ⚠️ Check bigint setup values with one shared checkAmount (bdfb78a)- Name setup checks check*, keeping assert* for public checks (
23cbdb8)
📖 Documentation
- Name the test command, where domain checks go, multi-call subjects, and how tests pin errors (
c031105) - Add setup check rules to AGENTS.md and match architecture and notes (
9b373c0) - Clarify leftOut's comment, notes.md's undefined wording and a test name (
3d935b8) - Treat an explicit undefined as a key left out (
2006149) - Only fix and review bugs that real use plausibly hits (
9dc6b03) - Assert on MockSetupError's class or code, not message text (
c489764) - Clarify that addTransaction mines a new block by default (
96dc5cf)
✅ Tests
- Set no-isolate on test script (
c8c000f) - Cover fee history's list checks and failRequests' method lists (
b56e23d)
❤️ Contributors
- Nathan Daniels (@nadaniels)
v0.1.1
v0.1.1 is the next patch release.
👉 Changelog
🏡 Chore
- ci: Add trusted publishing and uppt release flow (
8d2a2c2)
❤️ Contributors
- Nathan Daniels (@nadaniels)
v0.1.0
Initial release
Ethergeist - a mock Ethereum node behind a viem transport, for tests and demos. Each JSON-RPC request is answered with what the test registered; nothing executes.
Added
createMockRpc({ chain, blockNumber, timestamp, fees, debug }), withmock.transport()andmock.publicClient()for viem, andmock.request()for a raw JSON-RPC request.- Mocked contracts:
mock.contract({ abi, address, defaults }), with typedread,simulate,estimateGas, andwritenamespaces that mirror viem'sgetContract. A function mock.returns()a value or a resolver,.reverts()with the ABI's errors,.fails()as a node would, and takes.once()or.times(n). Multicall3 batches are answered call by call. - Matching on pinned args, with
match.any(),match.where(), andmatch.partial(): the most specific mock answers. When two are equally specific, limited ones (.once(),.times(n)) answer first, in the order they were registered; otherwise the one registered last answers. - Typed mocks for viem's public actions in
mock.actions(balances, code, storage, blocks, transactions, receipts, logs, gas prices and fee history, nonces, estimates, and sends), andmock.method()for any other JSON-RPC method. - A chain that sends build on:
mock.addTransaction(),mock.mine(),mock.setFees(), andcontract.emitandcontract.events(withcontractEvents()andtestLog()) for logs thatgetLogs(), watchers, and receipts find. mock.buildTransaction(),mock.buildReceipt(), andmock.buildLog()for values in viem's types, andtestAddress()andtestHash()for stable test values.- Node failures:
mock.failRequests()for HTTP errors, JSON-RPC errors, timeouts, and network failures, and named node errors (insufficient funds, nonce too low, and others) that viem sorts into its own error classes. - What the app asked:
mock.history,mock.calls,contract.calls,mock.unhandled,mock.formatHistory(), and thedebugoption. - Checks:
mock.assertNoUnhandled()andmock.assertAllUsed(), and theMockErrorfamily (MockCheckError,MockSetupError,MockNotFoundError,MockResolverError,MockInternalError) with stable error codes. - Shared setup:
mock.checkpoint()andrestore(),mock.reset(), andmock.clearCalls(). - ESM only, for Node 22.12 or later and browsers, with viem
^2.50.3and ox^0.14.22as peers, and types for TypeScript 5.8 or later.