Skip to Content
butr

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/testing

Drive 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 persisted

For 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.

PlatformOptional members
evmdisconnect, getBalance, getTransactionReceipt, requestAccounts, sendTx, signMessage, subscribe, switchChain
svmdisconnect, sendTx, signIn, signMessage, signTransaction, subscribe
suidisconnect, sendTx, signMessage, signTransaction, subscribe
bitcoindisconnect, sendTx, signMessage, signTransaction, subscribe
polkadotdisconnect, 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 account the fake does not expose rejects with AccountNotExposed. EVM addresses match case-insensitively. After disconnect(), a disconnected event or an empty accountsChanged, getAccounts() resolves [] and signing, sending and balance calls reject with NotConnected until the next connect().
  • A chain from another namespace, or outside the platform's registry, rejects with ChainMismatch. The EVM fake switches its accounts to a new chain before sendTx, 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. signMessage resolves your message as signedMessage.
  • getBalance reports balance in the native asset (ETH, SOL, SUI, BTC, DOT), one unit by default, and rejects a token: override it to fake token balances. Only the EVM fake has it unless you pass balance, matching the real adapters.
  • getSigner() resolves the signer option and rejects without one. The package registers no signer kind of its own, so your app's exhaustive switch (signer.kind) never grows a test-only case.

FakeAdapterOptions<P>

FieldDefaultNotes
chainPlatform"evm"Picks the platform and the adapter type.
id"fake"
name"Fake Wallet"
iconnone
accountsone plausible address on the platform's mainnetExposed accounts, active first.
balanceEVM: one unit of the native assetIn base units. On non-EVM platforms, passing it adds getBalance.
omit[]Optional members to leave off, to exercise the "this wallet cannot" path.
overridesnoneReplace any member but chainPlatform, e.g. a connect that rejects.
signernoneWhat 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 a ConnectorEvent to the manager, as the wallet would. getAccounts() follows it: a new account list replaces the exposed accounts, and disconnected or an empty list exposes none until the next connect().
  • listenerCount() returns the live subscribe listeners: zero once the manager has detached.
  • requests() lists every signing or sending request the fake accepted, oldest first, as FakeRequest: the method, the address it acted as, and the chain for 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:

FieldDefaultNotes
addressesone plausible address for the platformExposed on chain, active first. Ignored with accounts.
chainthe 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:

FieldDefaultNotes
wallets[]Connected wallets the previous session saved.
activenoneThe wallet the previous session left active; without it the manager picks the first restored wallet.
isUserDisconnectedfalseA 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:

  • getAccounts lists 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 with NotConnected, before the wallet is asked to sign.
  • A call without chain goes to the current chain. A chain from another namespace, or one the transport cannot reach, rejects with ChainMismatch. A reachable chain is routed for that one call or reached by switching the wallet's network, per the fixture's move. switchChain follows the same rules and tells subscribers.
  • subscribe forwards the wallet's account list as accountsChanged, active first, and an empty list as accountsChanged with no accounts, never as disconnected. 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,
});
FieldNotes
namePrefixes every test title.
addressesTwo addresses the wallet can expose on chain, each with a letter, so a case-changed copy differs.
chainThe chain the adapter is on once connected.
connectBuilds 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).
reachableA chain in the namespace the transport reaches. Omit for "fixed".
unreachableA chain in the namespace the transport cannot reach.
transactionsEvery method the adapter defines that takes chain, as a call with a payload the fake accepts.
activeOnlyThe 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.