Unit testing with Clarinet SDK
Learn how to write and run comprehensive unit tests for your Clarity smart contracts using the Clarinet SDK and Vitest.
Requirements
The SDK requires Node.js >= 18.0 and NPM to be installed. Volta is a great tool to install and manage JS tooling.
To follow this tutorial, you must have the Clarinet CLI installed as well.
Set Up the Clarity Contract and Unit Tests
Let us consider a counter
smart contract to understand how to write unit tests for our application requirements.
First, create a new Clarinet project with a counter
contract.
Below will be the content of our smart contract. It keeps track of an initialized value, allows for incrementing and decrementing, and prints actions as a log.
Migrating Between Clarinet v1 and Clarinet v2
Note: Clarinet v2 will be released in October 2023, and will create the right boilerplate files. But if a project has been created with Clarinet v1, the following script prepares the project to run the SDK and Vitest.
Executing this script in a Clarinet v1 project will initialise NPM and Vitest. It will also create a sample test file.
This script will ask you if you want to run npm install now; you can press enter to do so. This can take a few seconds.
The file tests/counter_test.ts
that was created by clarinet contract new counter
can be deleted.
You can also have a look at tests/contract.test.ts
. It's a sample file showing how to use the SDK with Vitest.
It can safely be deleted.
Unit Tests for counter
Example
Create a file tests/counter.test.ts
with the following content:
To run the test, go back to your console and run the npm test
command. It should display a report telling you that tests succeeded.
There is a very important thing happening under the hood here. The simnet
object is available globally in the tests, and is automatically initialized before each test.
You don't need to know much more about that, but if you want to know in detail how it works, you can have a look at the vitest.config.js
file at the root of you project.
Getting back to the tests, we just implemented two of them:
- The first test checks that the
increment
function returns the new value and saves it to thecount
variable. - The second test checks that an
print_event
is emitted when the increment function is called.
You can use Cl.prettyPrint(value: ClarityValue)
to format any Clarity value into readable Clarity code. It can be useful to debug function results or event values.
Note that we are importing describe
, expect
and it
from Vitest.
it
allows us to write a test.describe
is not necessary but allows to organize tests.expect
is use to make assertions on value.
You can learn more about Vitest on their website.
We also implemented some custom matchers to make assertions on Clarity variables (like toBeUint
).
The full list of custom matchers is available at the end of this guide.
Comprehensive Unit Tests for counter
Let us now write a higher coverage test suite by testing the decrement
and get-counter
functions.
These two code blocks can be added at the end of tests/counter.test.ts
.
Measure and Increase Code Coverage
To help developers maximize their test coverage, the test framework can produce a lcov
report, using --coverage
flag. You can set it in the scripts in the project package.json
:
Then run the script with the following command. It will produce a file named ./lcov.info
.
From there, you can use the lcov
tooling suite to produce HTML reports.
Costs Optimization
The test framework can also be used to optimize costs. When you execute a test suite, Clarinet keeps track of all costs being computed when executing the contract-call
, and displays the most expensive ones in a table.
To help developers maximize their test coverage, the test framework can produce a lcov
report, using --coverage
flag. You can set it in the scripts in the project package.json
:
And run the script with the following command. It will produce a file named ./costs-reports.json
.
For now, there isn't much you can do out of the box with a costs report. But in future versions of the clarinet sdk, we will implement features to help keep track of your costs, such as checking that function calls do not go above a certain threshold.
Produce Both Coverage and Costs Reports
In your package.json, you should already have a script called test:reports
like so:
Run it to produce both the coverage and the costs reports:
Run Tests in CI
Because the tests only require Node.js and NPM run, they can also be run in GitHub actions and CIs just like any other Node test.
In GitHub, you can directly set up a Node.js workflow like this one:
Custom Vitest Matchers
A set of Vitest matchers can be used to make assertions on Clarity values. They can check the return values of contracts, ensure that the value is actually a Clarity value, and provide nice error messages.
Check Clarity Type
toHaveClarityType(expectedType: ClarityType)
This matcher can be used to make sure that the value has the right Clarity Type, without checking its value.
It can also be used to check any type:
Response Type
The response type is noted (response <ok-type> <error-type>)
in Clarity.
It can be (ok <ok-type>)
or (err <error-type>)
.
They are called composite types, meaning that they contain another Clarity value.
toBeOk(expected: ClarityValue)
Check that a response is ok
and has the expected value. Any Clarity value can be passed.
toBeErr(expected: ClarityValue)
Check that a response is err
and has the expected value. Any Clarity value can be passed.
Consider that the counter
contract returns and error code 500 (err u500)
if the value passed to increment is too big:
Optional Type
The option type is noted (optional <some-type>)
in Clarity.
It can be (some <some-type>)
or none
.
Here, some
is a composite type, meaning that it contains another Clarity value.
toBeSome(expected: ClarityValue)
Consider a billboard smart contract that can contain an optional message:
toBeNone()
Considering the same billboard smart contract but with no saved message:
Simple Clarity Types
Custom assertion matchers are available for all types of Clarity values. They will check that the value has the right type and value.
toBeBool(expected: boolean)
Asserts the value of Clarity boolean (true or false).
toBeInt(expected: number | bigint)
Asserts the value of a Clarity int.
toBeUint(expected: number | bigint)
Asserts the value of a Clarity uint.
toBeAscii(expected: string)
Asserts the value of a Clarity string-ascii.
toBeUtf8(expected: string)
Asserts the value of a Clarity string-utf8.
toBePrincipal(expected: string)
Asserts the value of a Clarity principal value. The principal can be a standard or a contract principal.
toBeBuff(expected: Uint8Array)
Asserts the value of a Clarity buffer.
It takes as an input an ArrayBuffer (Uint8Array
).
Your test case will ultimately depends on how the Uint8Array is built. @stacks/transaction
can help building these buffers.
Other Composite Types
list
and tuple
are composite types, like ok
, err
, and some
. Meanning that they contain another Clarity value.
toBeList(expected: ClarityValue[])
Check that the value is a list
containing an array of Clarity values.
Considering a function that return a list of 3 uints:
toBeTuple(expected: Record<string, ClarityValue>)
Check that the value is a tuple
, it takes a JavaScript object to check the values. It's used in the tutorial above to check the value of the print event. It can also be used to check function call result.
The snippet below shows that composite types can be nested:
Last updated on