Testing
@usebutr/testing: fake adapters, fake connected wallets, fake persistence, and the contract suite every adapter runs.
@usebutr/testing provides test doubles for each platform's adapters. They
raise the same errors real adapters do, but carry a fixed set of members per
platform (see the table below). Install it as a dev dependency:
npm install --save-dev @usebutr/testingDrive a manager
Fakes go into sources through fromAdapters, like any built adapter, and
createFakePersistence replaces browser storage:
import { createWalletManager, fromAdapters } from "@usebutr/core";
import { createFakeAdapter, createFakePersistence } from "@usebutr/testing";
const metamask = createFakeAdapter({ id: "io.metamask", name: "MetaMask" });
const phantom = createFakeAdapter({ chainPlatform: "svm", id: "phantom", omit: ["signIn"] });
const locked = createFakeAdapter({
id: "locked",
overrides: { connect: () => Promise.reject(new Error("wallet is locked")) },
});
const storage = createFakePersistence();
const manager = createWalletManager({
sources: [fromAdapters([metamask, phantom, locked])],
storage,
});
const stop = manager.start();
await manager.connect("io.metamask");
metamask.emit({ type: "disconnected" }); // the wallet ends the session
storage.saves.at(-1); // what the manager persistedFor components, pass the same config to WalletManagerProvider. A test may
build it inline: the provider reads it once per mount.
import type { WalletManagerConfig } from "@usebutr/core";
import { fromAdapters } from "@usebutr/core";
import { WalletManagerProvider } from "@usebutr/react";
import { createFakeAdapter, createFakePersistence } from "@usebutr/testing";
const config: WalletManagerConfig = {
sources: [fromAdapters(createFakeAdapter({ id: "io.metamask", name: "MetaMask" }))],
storage: createFakePersistence(),
};
render(
<WalletManagerProvider config={config}>
<WalletPicker />
</WalletManagerProvider>,
);createFakeAdapter(options?): FakeAdapter<P>
An EVM adapter unless chainPlatform says otherwise, with the members a real
wallet on that platform has, typed to it: createFakeAdapter({ chainPlatform: "svm" })
is a FakeAdapter<"svm">, an SvmAdapter plus the test controls.
| Platform | Optional members |
|---|---|
evm | disconnect, getBalance, getTransactionReceipt, requestAccounts, sendTx, signMessage, subscribe, switchChain |
svm | disconnect, sendTx, signIn, signMessage, signTransaction, subscribe |
sui | disconnect, sendTx, signMessage, signTransaction, subscribe |
bitcoin | disconnect, sendTx, signMessage, signTransaction, subscribe |
polkadot | disconnect, signMessage, subscribe |
Only the EVM fake has switchChain. A real Wallet Standard adapter on svm,
sui, bitcoin or polkadot has it when the wallet advertises more than one
chain; pass it through overrides to test that path.
It passes the adapter contract suite, so code under test meets the same failures it would in production:
- An
accountthe fake does not expose rejects withAccountNotExposed. EVM addresses match case-insensitively. Afterdisconnect(), adisconnectedevent or an emptyaccountsChanged,getAccounts()resolves[]and signing, sending and balance calls reject withNotConnecteduntil the nextconnect(). - A
chainfrom another namespace, or outside the platform's registry, rejects withChainMismatch. The EVM fake switches its accounts to a new chain beforesendTx, as a real EVM wallet does, and tells its listeners; the other fakes route the one call, as Wallet Standard does. - Hashes and signatures are distinct on every call, so two results never
compare equal by accident.
signMessageresolves your message assignedMessage. getBalancereportsbalancein the native asset (ETH,SOL,SUI,BTC,DOT), one unit by default, and rejects atoken: override it to fake token balances. Only the EVM fake has it unless you passbalance, matching the real adapters.getSigner()resolves thesigneroption and rejects without one. The package registers no signer kind of its own, so your app's exhaustiveswitch (signer.kind)never grows a test-only case.
FakeAdapterOptions<P>
| Field | Default | Notes |
|---|---|---|
chainPlatform | "evm" | Picks the platform and the adapter type. |
id | "fake" | |
name | "Fake Wallet" | |
icon | none | |
accounts | one plausible address on the platform's mainnet | Exposed accounts, active first. |
balance | EVM: one unit of the native asset | In base units. On non-EVM platforms, passing it adds getBalance. |
omit | [] | Optional members to leave off, to exercise the "this wallet cannot" path. |
overrides | none | Replace any member but chainPlatform, e.g. a connect that rejects. |
signer | none | What getSigner() resolves: any WalletSigner. |
import type { WalletSigner } from "@usebutr/core";
const signer: WalletSigner = {
kind: "eip1193",
provider: { on: () => {}, removeListener: () => {}, request: () => Promise.resolve(null) },
};
const metamask = createFakeAdapter({ id: "io.metamask", signer });Controls
FakeAdapterControls, on every fake:
emit(event)delivers aConnectorEventto the manager, as the wallet would.getAccounts()follows it: a new account list replaces the exposed accounts, anddisconnectedor an empty list exposes none until the nextconnect().listenerCount()returns the livesubscribelisteners: zero once the manager has detached.requests()lists every signing or sending request the fake accepted, oldest first, asFakeRequest: themethod, theaddressit acted as, and thechainfor methods that take one.
createFakeConnectedWallet(options?): FakeConnectedWallet<P>
A pool entry as the manager builds it after connect: a fake adapter plus
the accounts it exposes, so the two never disagree. Hand it to components and
helpers that take a ConnectedWallet; drive it through
wallet.connector.emit.
import { EVM_CHAINS } from "@usebutr/core";
import { createFakeConnectedWallet } from "@usebutr/testing";
const phantom = createFakeConnectedWallet({ chainPlatform: "svm", id: "phantom" });
render(<WalletCard wallet={phantom} />);
const multi = createFakeConnectedWallet({
addresses: ["0xabc…", "0xdef…"],
chain: EVM_CHAINS.base,
});FakeConnectedWalletOptions<P> takes every adapter option plus:
| Field | Default | Notes |
|---|---|---|
addresses | one plausible address for the platform | Exposed on chain, active first. Ignored with accounts. |
chain | the platform's mainnet (EVM_CHAINS.ethereum, SVM_CHAINS.mainnet, …) | For the generated accounts. |
account is always accounts[0], as on a real pool entry.
createFakePersistence(seed?): FakePersistence
A WalletPersistence over the production createWalletStorage with
in-memory drivers, so load() decodes and validates exactly as it does in the
browser. The seed is what the first load() finds, as if a previous session
had saved it:
| Field | Default | Notes |
|---|---|---|
wallets | [] | Connected wallets the previous session saved. |
active | none | The wallet the previous session left active; without it the manager picks the first restored wallet. |
isUserDisconnected | false | A manual disconnect earlier in the same session. |
saves lists every state the manager handed to save, oldest first.
Seed it to test hydration: the manager silently reconnects the stored wallet once its fake adapter is announced.
import { createWalletManager, fromAdapters } from "@usebutr/core";
import { createFakeConnectedWallet, createFakePersistence } from "@usebutr/testing";
const wallet = createFakeConnectedWallet({ id: "io.metamask", name: "MetaMask" });
const storage = createFakePersistence({ wallets: [wallet] });
const manager = createWalletManager({
onHydrated: ({ restoredIds }) => {
// ["io.metamask"]
},
sources: [fromAdapters(wallet.connector)],
storage,
});
manager.start();Adapter contract suite
@usebutr/testing/contract exports describeAdapterContract, the Vitest suite
every butr adapter package runs against its adapters. Adapter authors run it
against their own adapter, over a fake of their wallet. It covers what every
adapter does alike, whatever its transport:
getAccountslists every exposed account, active first, on the current chain, and resolves[]when the wallet exposes nothing.- A call acts as the active account, or as a requested exposed one. EVM
addresses match case-insensitively; every other namespace matches exactly.
An unexposed account rejects with
AccountNotExposed, and a wallet that exposes nothing withNotConnected, before the wallet is asked to sign. - A call without
chaingoes to the current chain. A chain from another namespace, or one the transport cannot reach, rejects withChainMismatch. A reachable chain is routed for that one call or reached by switching the wallet's network, per the fixture'smove.switchChainfollows the same rules and tells subscribers. subscribeforwards the wallet's account list asaccountsChanged, active first, and an empty list asaccountsChangedwith no accounts, never asdisconnected. Nothing arrives after unsubscribing.
Install vitest alongside @usebutr/testing; the contract entry imports it.
Call the suite at the top level of a test file, once per adapter:
import type { EvmAdapter } from "@usebutr/core";
import { EVM_CHAINS } from "@usebutr/core";
import type { ObservedCall } from "@usebutr/testing/contract";
import { describeAdapterContract } from "@usebutr/testing/contract";
import { buildMyAdapter } from "../adapter";
import { createMyFakeWallet } from "./fake-wallet";
describeAdapterContract<EvmAdapter>({
addresses: [
"0x52908400098527886E0F7030069857D2E4169EE7",
"0x8617E340B3D01FA5F11F306F4090FD50E238070D",
],
chain: EVM_CHAINS.ethereum,
connect: async (addresses) => {
const calls: Array<ObservedCall> = [];
const wallet = createMyFakeWallet(addresses, (call) => calls.push(call));
return {
adapter: buildMyAdapter(wallet),
lastCall: () => calls.at(-1),
reportAccounts: (reported) => wallet.emitAccounts(reported),
};
},
move: "switch",
name: "My wallet",
reachable: EVM_CHAINS.polygon,
transactions: { sendTx: (adapter, options) => adapter.sendTx?.({}, options) },
unreachable: EVM_CHAINS.base,
});| Field | Notes |
|---|---|
name | Prefixes every test title. |
addresses | Two addresses the wallet can expose on chain, each with a letter, so a case-changed copy differs. |
chain | The chain the adapter is on once connected. |
connect | Builds an adapter whose wallet exposes addresses, active first, connected where the transport allows it. [] builds one exposing nothing. |
move | "route" (Wallet Standard, WalletConnect), "switch" (injected EVM, UniSat, sats-connect) or "fixed" (Ledger, injected Polkadot). |
reachable | A chain in the namespace the transport reaches. Omit for "fixed". |
unreachable | A chain in the namespace the transport cannot reach. |
transactions | Every method the adapter defines that takes chain, as a call with a payload the fake accepts. |
activeOnly | The transport signs only as its active account (UniSat). |
connect resolves a ContractWallet: the adapter, lastCall() returning the
last signing or sending request the fake wallet received as an ObservedCall
(address, chain), and reportAccounts(addresses) for transports whose
wallet pushes account changes. A suite skips what the adapter does not define:
no switchChain, no signMessage, or no reportAccounts.
Types
FakeAdapter, FakeAdapterControls, FakeAdapterOptions, FakeRequest,
FakeConnectedWallet, FakeConnectedWalletOptions, FakePersistence. From
@usebutr/testing/contract: AdapterContractFixture, ContractWallet,
ObservedCall, TransactionCall.
Source: packages/testing/src (fake-adapter.ts, fake-connected-wallet.ts,
fake-persistence.ts, adapter-contract.ts) in the butr
repository.