Caleb Gates
Caleb Gates

Reputation: 1024

Debug hardhat solidity tests In WebStorm

After running Hardhat tests in the console with npx hardhat test I decided that being able to set break points would help me iterate faster.

How can I get Webstorm to run the underlying functions started by npx hardhat test so that I can use the built in Debugger?

Upvotes: 3

Views: 2007

Answers (4)

Alexey
Alexey

Reputation: 7257

Install ts-mocha as mentioned by @Fedy_

# remember to install mocha if you don't have it already (npm i -D mocha)

npm i -D ts-mocha

# install recent Mocha and Expect @types packages for best DX
npm i -D @types/mocha @types/expect

Add ts-mocha path to run Run/Debug configurations of IntelliJ IDEA

enter image description here

Upvotes: 1

Fedy_
Fedy_

Reputation: 491

If you're use typescript you need to import ts-mocha instead of mocha

Upvotes: 1

allen
allen

Reputation: 456

  1. Create or open the package.json file for your Hardhat project.
  2. Add a test NPM run script and save the file. Your package.json should look something like this.
{
  "name": "hardhat-project",
  "scripts": {
    "test": "hardhat test"
  },
  "devDependencies": {
    "@nomiclabs/hardhat-ethers": "2.0.2",
    "@nomiclabs/hardhat-waffle": "2.0.1",
    "chai": "4.3.4",
    "ethereum-waffle": "3.4.0",
    "ethers": "5.4.4",
    "hardhat": "2.6.0"
  }
}
  1. In the left gutter of the editor pane, a little play icon should appear, click it and then click Debug "test".

I go through the instructions in a little more detail here, but this is the general idea. https://allendefibank.medium.com/how-to-debug-solidity-contracts-in-webstorm-hardhat-2ea0d3c4d582

Upvotes: 4

Caleb Gates
Caleb Gates

Reputation: 1024

I've since discovered that hardhat runs mocha under the hood.

To debug in WebStorm you can:

  1. delete your existing configurations
  2. create a new mocha configuration
  3. set any configurations in 'Node options'. Note: since I'm forking the main net it takes a while for tests to start so I added the --timeout 10000 because mocha's default timeout is only 2000ms
  4. select the mocha package, WebStorm doesn't select it by default
  5. set your test file pattern
  6. add const {ethers} = require('hardhat'); to your test file because it is no longer injected by hardhat during run time.
  7. If the green debug icon does not appear I had success in closing and reopening WebStorm.

At this point I could successfully set break points in my test file but not in the MyContract.sol file. This is not surprising given that the contract is compiled before its run.

enter image description here

enter image description here

Upvotes: 4

Related Questions