Learn how to write and run integration tests for your Clarity smart contracts using the Clarinet JS SDK and Vitest.
This guide demonstrates how to write integration tests for Clarity smart contracts using the Clarinet JS SDK and Vitest. You'll learn to set up the testing environment, write tests for a DeFi contract, and generate coverage reports.
In this guide, you will:
Set up the Clarinet JS SDK in your project.
Write integration tests for the stx-defi smart contract.
Run tests and generate coverage reports.
Requirements
This guide requires Node.js >= 18.0 and NPM. We recommend using Volta to manage your JavaScript tooling.
First, install the Clarinet JS SDK and Vitest as development dependencies in your project:
This will create a tests directory in your project root and add a vitest.config.ts file:
This configuration enables global test functions and sets up coverage reporting.
Write Integration tests for stx-defi
Create a new file stx-defi.test.ts in the tests directory. We'll start by importing the necessary functions from the Clarinet SDK and setting up the test environment:
This setup creates a new Chain instance for each test, ensuring a clean state. It also retrieves account information for the deployer and two test wallets.
Now, add some tests for the main functions of our DeFi contract:
These tests verify the deposit and borrow functionalities of the contract. They simulate transactions, check for successful execution, and verify the resulting state changes.
To run your tests, add the following script to your package.json:
Now you can run your tests with:
To generate a coverage report, use:
This will run your tests and produce a detailed coverage report, helping you identify any untested parts of your contract.
By following this guide, you've set up a testing environment for your Clarity smart contracts using the Clarinet JS SDK and Vitest. You've written tests for key functions of a DeFi contract and learned how to run tests and generate coverage reports. This approach allows you to catch bugs early and ensure your contracts behave as expected before deployment.