Better testing
Write scripts to automate your testing and deployments
Framework
It can be instructive to directly interact with contracts via the CLI as we are learning, but it is impractical once we are dealing with multiple contracts, calls and environments. To help you deploy and test more efficiently, Completium comes with two TypeScript packages for interacting with smart contracts:
@completium/dapp-ts@completium/experiment-ts
We will use dapp-ts directly in our Next application. It is meant to be ran from the browser. We will use experiment-ts for local development.
Installation
We need to add some dependencies to use our scripts:
yarn add --dev mocha
yarn add --dev @completium/experiment-ts@0.1.13 ts-mocha@10.0.0
yarn add --dev @types/mocha@9.1.1 @types/node@20.2.3 Script
Create a new file at ./tests/deployAndTest.ts
Before we start writing our script, we'll generate TypeScript bindings of our smart contract, so we can easily interact with them.
npx completium-cli generate binding-ts * --input-path ./contracts --output-path ./tests/bindingsIt will generate one TS file per contract, in the ./tests/bindings folder.
The bindings are TypeScript modules that expose smart contract features such as entrypoints, assets and variables. Each contract produces a TypeScript class, whose methods are the contract features.
The generate binding-ts script extracts information from the contract code, including type definitions, and function interfaces. The script should be run every time changes are made to the smart contract source. The generated files should not be directly modified, as they will be overwritten.
In deployAndTest.ts, we'll use mocha to create test cases, first the required imports:
Now we'll instantiate our contracts that are now TS classes:
And get test accounts:
Test cases are grouped in describe blocks, and each test will be in a it block. See mocha's documentation for more details.
The first block simply deploys each contract. We also print the contract addresses as they can be useful when we actually deploy our contracts.
Note how the parameters for the deployment are passed as parameters in the deploy function.
You can test your script with the following command:
The next block will register the Zombie and Brainz NFT, again with their magic token metadata byte string.
Let's test the mint entrypoint. This next test will mint 1 Zombie (id 1) with Alice's wallet and check her balance.
In this block, add the mint test:
And list it for sale in the it block:
As with the CLI testing, we'll check that the buy will fail if the marketplace is not an operator:
Now let's approve the marketplace for all of Alice's tokens:
If we try to buy again, but with insufficient funds:
Now with the correct amount, the purchase will go through:
Last updated