Tips for Testing in Hardhat

How I test and debug my smart contracts.

Elim Poon
Coinmonks
Published in
3 min readFeb 13, 2022

--

Image by @whoisdenilo on Unsplash.com

Introduction

This article will be an extension of the official Hardhat docs. If you have not already, I would highly suggest that you take a look there first. With that said, let’s get right to it!

it

Should use console.log()

If you have done any sort of programming, you know how helpful it is to be able to read your variables during code execution. I personally love to spam this method, particularly console.log("Got here!"); when I am trying to locate errors. But using this within your smart contract is a bit tricky. First you have to import hardhat console by adding the following line to your Solidity code:

import "hardhat/console.sol";

Then create a Hardhat node to run your code within. You can do this with the following terminal command:

npx hardhat node

You can also fork mainnet or a testnet if needed. Now when you run your tests/code (in a different terminal window), you will be able to see the values that you console.logged in the node terminal!

An alternative is to use a service called Tenderly that will allow you to view console.logs from deployed contracts. This method is more tedious but does allow you to test in production.

Should use .only to isolate tests

Sometimes you .only want to run certain tests in your suite of millions. You can do this by adding .only after the describe or it commands like so:

describe.only("Blah blah blah",...);

Hardhat will then only run that particular test, ignoring all other tests (and files). You can .only multiple tests, but there are certain rules that I have not yet had the time to figure out. Remember to remove the modifier when you are done.

Should organize tests

If you have lots of tests (security is important in crypto, or so they say), then the .only method might not be enough. Luckily, Hardhat has an option that will allow you to specify where the tests are located. You can group your tests into folders and change the specified folder path in the config file, running only the tests within that folder.

Closing words

As you have probably already noticed, documentation in the crypto space ranges from highly limited to non-existent. Thus, even as a non-writer, I feel compelled to take up the mantle and shine some light into this vast archival void. Hopefully, readers will find my articles helpful. I am new to this, so comments are highly welcomed. Happy coding!

Join Coinmonks Telegram Channel and Youtube Channel learn about crypto trading and investing

Also Read

--

--

Elim Poon
Coinmonks

blockchain engineer, computer geek, fiction enjoyer, gamer