Repository navigation
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 range or a block hash, not one flat shape:- a
LogsCallbuilt by hand must be one complete form; - a filter or context typed by hand in the old flat shape no longer fits
mock.actions.getLogs(). UsePartial<LogsCall>andLogsContextinstead; - a recorded call spread into a pin with a range field overridden needs a
blockHash === undefinedcheck first; - with
exactOptionalPropertyTypeson, a matcher atfromBlock,toBlock, orblockHashneeds a type annotation.
- a
mock.method()refuses a reserved method at compile time, where it used to throw at registration. A name typed as a union that includes a reserved method no longer compiles, and that's most likely viem's method union. Neither does a generic pass-through. Type either one asExclude<…, ReservedMethod>.- Messages: many misses, refusals, and history lines are reworded. Strings are now quoted (
blockTag: "latest",got "21000".), while hex stays bare. A contract's mock is named with its namespace, aswrite.withdraw(150n), including in resolver, matcher, and.returns()errors. As a result,assertNoUnhandled()lists one function's failures in different namespaces as separate lines. Assert on the error class or itscode, not on its text.
Features
mock.method()suggests JSON-RPC method names as you type: viem's names, minus the ones that have a typed action. It still takes any string.- Misses name the mocks that came close:
- a contract's miss lists the action mocks that would have matched, and the mocks on the function's other overloads;
- an action's miss says when the address belongs to a registered contract;
- a simulation's miss says that a
writemock doesn't answer simulations; - a miss says "the call has no gas" when the call leaves out a key the mock pins.
- After a
restore()orreset(), a miss names the mocks the restore removed. This works for contracts, typed actions, and raw methods. - History shows what each request asked as soon as it arrives. A faulted, pending, or partly failed request's entry shows its decoded call. A batch lists every call with its true count, and marks the calls its request never reached as
– not reached. - New exported types:
FaultContext, thefailevery resolver's context has, for a helper shared between resolvers;RefusalContextandMockRefusalAnswers;MockCallOutcome;SuggestedMethodandReservedMethod.
- A first example app,
examples/uniswap-v2-limit-order: a Uniswap V2 limit-order bot with a local account, and its tests. - The README has a recipe for a per-test checkpoint, and says what a test's mock needs in order to override a shared setup's mock.
Bug Fixes
- With a local account, a missing or wrongly pinned write mock was reported as a missing
estimateGasmock, because viem estimates before it sends. The miss now names the send's mock first. - A
match.where()predicate at an optional position (an action's field, afromorvaluepin, or amatch.partial()field) is typed withoutundefined, so it compiles withoutexactOptionalPropertyTypes. With the flag on, agetLogsmock takes a predicate at bothfromBlockandtoBlock, and a named predicate with an optional parameter fits an optional param. match.partial()around an action's whole params, as inmock.actions.getBalance(match.partial({ address: match.where(…) })), takes matchers inside it. Its fields get the same checks as the plain object: a malformed address throws at registration, a storage slot is padded, and a miss lists it as the plain object. Amatch.where()inside amatch.partial()nested in another compiles withoutexactOptionalPropertyTypes.- Requests made at once reach their mocks in the order they were made, raw sends included, and they settle sooner.
- A static
writeoutcome is kept as it was given: changing the object after.returns()no longer changes the answer. - History decodes an action estimate mock's revert of a registered contract's function with that contract's ABI. It shows
✗ reverted: Paused(7n)instead of the raw data. assertAllUsed()reports the same mismatch a miss does, and runs a predicate only where matching would.- History lines mark a retry before its outcome. A request whose call didn't decode now prints its params as sent, instead of
getBalance(*). - A miss no longer says a restore removed a contract that has been registered again, and it gives the nested-
describehint only once.
👉 Changelog
🚀 Enhancements
⚠️ Remove revert() from a send mock's resolver (45f10a8)- Decode each request as it arrives, so history shows what it asked (
5ba8e19) - Add a Uniswap V2 limit-order bot example (
1c42c15) - Name a raw method's mocks removed by a restore (
5fc39da) - mock.method() suggests method names (
f9d04c0) ⚠️ mock.method() refuses a reserved method at compile time (6571123)⚠️ LogsCall is a block range or a block hash (50732a5)⚠️ A send mock's resolver returns its logs (a3122bf)⚠️ A node's refusal by name is .refuses(), not .fails() (12a1dd6)- List sendTransaction mocks on the actions' estimate miss (
2ad7d96) - Name the other side's mocks and contracts in a miss (
03b038a) ⚠️ Only a contract's mocks answer its functions (02694a9)- Note the mocks the last restore removed when a call misses (
dda7023)
🩹 Fixes
- Show a registered contract's call as the contract's under an unused action mock (
4b32b7c) - Fold an unused mock's identical received calls into one line (
23bf16e) - Say a send mock answers its estimate, not that it implies it (
0bfa419) - Treat an action's whole params in match.partial() as the plain object (
cffea8b) ⚠️ Give a send's and an estimate's call "0x" data when they have none (bd79b63)⚠️ Rank an empty list as an exact value (0820e69)⚠️ Count match.any() toward which mock answers (01f7ca7)- Type a match.where() matcher without undefined (
eef41c3) - Say when a call leaves out the key a mock pins (
ef38faf) ⚠️ No pin matches a value the call leaves out (eff88f0)- Type a match.where() predicate without undefined (
60583d1) - Name a contract mock's namespace in its errors (
aeb3b44) - Name a contract mock's namespace in its messages (
f310dec) - Say that a write mock doesn't answer simulations (
55281b2) - Name the send's mock when a send's estimate misses (
3428f8b) - Recover a raw send's signer synchronously, keeping its order (
38ea1af) - Print a request's params in history when its call isn't decoded (
22f9aaa) - Mark a retry before its outcome in history (
2abe8af) - Add missing oxford comma (
a320154) - Quote strings in messages & history, except hex (
629fac9) - Refuse a runner's matcher before an action's pin copies it (
1960550) - Refuse a contract mock whose args can't fit its function (
f3e103b) - Treat an undefined in a pin as left out, or refuse it (
dce0108) - Say the nested-describe hint once in a miss (
6bbc4a6) - assertAllUsed() names the mismatch matching names (
1e6d01b) - Name the other overloads' mocks in a contract's miss (
80937ca) - Say why an action mock didn't answer a contract's function (
b1700e7) - Don't say a restore removed a contract that's registered again (
d7e3d84) - Hold a static write outcome as given, like every other answer (
591749b)
💅 Refactors
- Tell the mock engine once how to name a mock (
b234454) - Declare a resolver's fail once, as FaultContext (
998b255) - Name the wide object check isNonArrayObject (
4891f59) - Give each contracts file one concept for pinning args (
68d430b) - Number history entries by their position (
c1a4071) - Run the send resolver guard once, in the send engine (
eb8b305) - Name the setup checks that throw MockSetupError check* (
fdc17f9) - Move the mock set into actions/mockSet.ts (
fa19e5a) - Answer sends and their estimates in actions/sends.ts (
ecaeffb) - Build a contract's turn record once (
08a02a4) - Name actions/codec.ts and transactions/writes.ts for what they hold (
42ea46f) - Read chainId directly from the state's chain (
7371ab5) - Read each contract namespace's answers from one catalog (
896d263) - Hold a mock's answer as a tagged union (
b98f27f) - Drop topicsMatch's unreachable topic check (
225f207) - Remove dead code from coverage report (
352eb1f) - Let the history entry take reports and settle itself (
aaf9797) - Keep the block at registration in the action table, with one encode context (
63d6a99) - Place a send in the transaction store (
429520a) - Build receipts in the transaction store, and place logs once (
f449da4) - Ask a send mock for its implied estimate in one place (
27178c5)
📖 Documentation
- Show the per-test checkpoint recipe, and what an override needs to win (
c7b2335) - Fill README gaps surfaced from example app (
cfeb944) - Use Oxford comma throughout (
26ac464) - Scope the viem watch-from-block-0 pitfall to viem <2.57.13 (
f8ccb0c) - Tweaks to required versions & test overrides (
b5821c1) - Drop roadmap version from README; inline & docs comments pass (
f5d27fc) - Say what a fault's handle does after a restore (
27387b8)
🏡 Chore
- Update stryker timeout (
b2ea851) - Keep worktrees out of lint/format checks (
bcbc947) - Raise dev ranges with each Dependabot bump (
9816006) - Add examples workspace (
65826be) - Tidy messages, test names and comments (
1d1b10f)
✅ Tests
- Pin match.partial() picking a struct's overload over a scalar's (
b9e4ee7) - Pin what a left-out from and a raw method's missing param don't match (
a713f4e) - Pin the mock engine's matching before its refactor (
82984ab) - Check each example test's own mocks, and drop the shared send helper (
7031daa) - Choose an ambiguous overload as viem does, at any viem version (
3f03856) - Cover unpinned behaviors from latest mutation run (
29e5dd2) - Give each action's type tests their own describe (
9935109) - Debug: false logs nothing (
ddbe4a4) - Close additional gaps in testing coverage (
1bd758d) - Add tests to easily reachable coverage gaps (
45f38ab) - Pin getFeeHistory's refusal edges, and show history's view as viem returns it (
0b18c72)
❤️ Contributors
- Nathan Daniels (@nadaniels)