Writing tests
Problem
I want to write tests in TypeScript
Solution
Tevm is the most flexible and robust way to write tests in TS yet.
This solution uses following technology
Vitest
for writing TypeScript testsTevm Viem
to run an anvil compatable devnet in TypeScript using the viem apiTevm Bundler
as an easy way to use contract abis in TypeScript testsTevm Server
to turn Tevm Node into a HTTP server for our tests
:::tip [tevm test] An opinionated testing library is on the roadmap for Tevm. If you want to suggest features you would like to see consider opening an issue. :::
Example
Though Tevm is built mainly for the browser, it’s anvil compatability, flexible ergonomic api, and support for easily modifying the EVM make it an amazing testing library as well. Tevm features:
- Ergonomically and typesafely import contracts directly into your tests. Libraries like vitest will automatically recompile your contracts when they change
- Modify the EVM state easily via cheat methods like
setAccount
and account impersonation - Mock entire contracts easily in a typesafe way via writing JavaScript contracts
To start let’s have Tevm fork optimism and start a node.js server
We can use memoryClient to modify any account, it’s contract bytecode, or it’s contract storage using setAccount
In addition to setAccount Tevm MemoryClient supports all viem test actions
We can mock out a contract via replacing it with a different solidity contract.
You can also write a JavaScript precompile contract to mock if more convenient.
Comparison to alternatives
Anvil
Pros:
- Anvil is currently more mature as Tevm is in Beta
- Anvil written in rust is a faster though not much faster as both are bottlenecked by network forking
Cons:
- Limited feature set to do things like mock contracts in JavaScript compared to Tevm
- Much harder to set up in a JS testing environment
- Unlike hardhat or Tevm it has no awareness of your contracts
- Tevm features a level of typesafety and autocomplete missing if you use anvil
Hardhat
Pros:
- More mature as Tevm is in Beta
- Might integrate into a setup you are already using for contract deployments
Cons:
- Hardhat is opinionated about testing framework. Tevm modularly works with any framework including Vitest and Bun.
- Tevm is significantly less boilerplate to set up
- Tevm supports advanced features that Hardhat does not support
- Tevm features a level of typesafety and autocomplete missing from Hardhat