Skip to content
On this page

Test Client โ€‹

A Test Client is an interface to "test" JSON-RPC API methods accessible through a local Ethereum test node such as Anvil or Hardhat such as mining blocks, impersonating accounts, setting fees, etc through Test Actions.

The createTestClient function sets up a Test RPC Client with a given Transport.

Import โ€‹

ts
import { createTestClient } from 'viem'

Usage โ€‹

Initialize a Client with your desired Chain, Transport (e.g. http) and mode (e.g. "anvil").

ts
import { createTestClient, http } from 'viem'
import { foundry } from 'viem/chains'

const client = createTestClient({
  chain: foundry,
  mode: 'anvil',
  transport: http(), 
})

Then you can consume Test Actions:

ts
const mine = await client.mine({ blocks: 1 }) 

Extending with Public & Wallet Actions โ€‹

When interacting with a Ethereum test node, you may also find yourself wanting to interact with Public Actions and Wallet Actions with the same chain and transport. Instead of creating three different Clients, you can instead just extend the Test Client with those actions:

ts
import { createTestClient, http, publicActions, walletActions } from 'viem'
import { foundry } from 'viem/chains'

const client = createTestClient({
  chain: foundry,
  mode: 'anvil',
  transport: http(), 
})
  .extend(publicActions)
  .extend(walletActions)

const blockNumber = await client.getBlockNumber() // Public Action
const hash = await client.sendTransaction({ ... }) // Wallet Action
const mine = await client.mine({ blocks: 1 }) // Test Action

Parameters โ€‹

mode โ€‹

  • Type: "anvil" | "hardhat" | "ganache"

Mode of the Test Client.

ts
const client = createTestClient({
  chain: foundry,
  mode: 'anvil', 
  transport: http(), 
})

transport โ€‹

Transport of the Test Client.

ts
const client = createTestClient({
  chain: foundry,
  mode: 'anvil', 
  transport: http(),  
})

account (optional) โ€‹

  • Type: Account | Address

The Account to use for the Client. This will be used for Actions that require an account as an argument.

Accepts a JSON-RPC Account or Local Account (Private Key, etc).

ts
import { privateKeyToAccount } from 'viem/accounts'

const client = createTestClient({
  account: privateKeyToAccount('0x...') 
  chain: mainnet,
  transport: http(),
})

chain (optional) โ€‹

Chain of the Test Client.

ts
const client = createTestClient({
  chain: foundry, 
  mode: 'anvil',
  transport: http(), 
})

name (optional) โ€‹

  • Type: string
  • Default: "Test Client"

A name for the Client.

ts
const client = createTestClient({
  chain: foundry,
  mode: 'anvil', 
  name: 'Anvil Client',  
  transport: http(),
})

pollingInterval (optional) โ€‹

  • Type: number
  • Default: 4_000

Frequency (in ms) for polling enabled Actions.

ts
const client = createTestClient({
  chain: foundry,
  mode: 'anvil', 
  pollingInterval: 10_000,  
  transport: http(),
})

Released under the MIT License.