Use your favorite unit test framework to test smart contracts using the NEO•ONE client APIs.
The NEO•ONE toolchain generates a helper function called withContracts
in src/neo-one/test.ts
that makes testing a breeze:
By convention, smart contract tests are located in src/__tests__
, but you can place them wherever you’d like.
Note
In all of our examples we’ll use Jest for the testing framework, but the
withContracts
function is framework agnostic, so you may use it with any testing framework.
The withContracts
function starts up a fresh network for each test case, compiles all of your smart contracts, deploys them to the local network, pre-configures a Client
as well as a DeveloperClient
and creates the smart contract APIs. It then passes these tools as properties of an object to an async callback function where your testing logic should reside. The properties available to your function are:
In addition to the properties listed above, the object will contain a smart contract API object property for each smart contract in your project, configured with the Client
at the client
property. The example at the beginning of this section shows how you could access the smart contract API for a smart contract called Token
.
Within the callback to the withContracts
function, we can test our smart contracts using the same NEO•ONE client APIs that we use to interact with the contract in production (and that we’ve discussed over the previous 2 chapters).
To run tests quickly, the network and clients are setup to run consensus immediately with every transaction. This way, tests do not have to wait for blocks to be produced every 15 seconds. If you’d like to turn off this behavior, or configure other aspects of withContracts
, you may pass in an options object as the second parameter:
For example, to turn off automatic consensus:
DeveloperClient
has not been thoroughly tested for N3 yet and may not work at this point in time.
DeveloperClient
is a class that is configured to point at a local development network. This class provides methods that are useful during testing:
runConsensusNow(): Promise<void>
- trigger consensus to run immediately.fastForwardOffset(seconds: number): Promise<void>
- fast forward the local network by seconds
into the future. Use this method to test time-dependent smart contracts.fastForwardToTime(seconds: number): Promise<void>
- fast forward to a particular unix timestamp in the future.reset(): Promise<void>
- reset the local network to it’s initial state starting at the genesis block.getSettings(): Promise<PrivateNetworkSettings>
- Get the current settings of the private network.updateSettings(options: Partial<PrivateNetworkSettings>): Promise<void>
- update settings for the private network. Currently only has a property for controlling the seconds per block.getNEOTrackerURL(): Promise<string | undefined>
- fetches the NEO Tracker URL for the project.Putting it all together, we might test a time dependent ICO contract like so: