Is there a way to debug JS unit tests for smart contracts? I use VS Code for development, and when I try to run a Mocha debugger it complains that artifacts is not defined. I briefly looked at truffle code, it looks like it adds artifacts, contract and some other global js variables when it runs the unit tests. Is there a way for me to add those explicitly in the JS unit test file so I could debug that unit test file?
- 1,147
- 1
- 12
- 19
2 Answers
Your lucky day (had to solve this few days ago):
See that you have truffle-core locally in your project. If not, do:
npm install truffle-core
Then use a configuration similar to this: ( Debug -> Open Configurations )
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "truffle test (debugable)",
"cwd": "${workspaceFolder}",
"program": "${workspaceFolder}\\node_modules/truffle-core/cli.js",
"args": [
"test"
]
}
]
}
Or add a new one (simple "node" launch, then edit it)
If your code does not spawn another node process (brings trouble which are essentially an node.js bug), you should be good.
- 176
- 1
- 4
The accepted solution above can also be used to start the debugger from command line and debug in node inspector (in Chrome dev tools):
npm install truffle-core
node --inspect-brk ./node_modules/truffle-core/cli.js test test/test_to_debug.js
UPDATE: truffle-core https://github.com/trufflesuite/truffle-core
⚠️ This repo is deprecated ⚠️ Truffle has moved all modules to a monorepo at trufflesuite/truffle. See you over there!
node --inspect-brk ./node_modules/truffle/build/cli.bundled.js test test/test_to_debug.js
Now open the debugger:
- Open chrome://inspect page and click the "Open dedicated DevTools for Node" link
- The cli.js file should be opened with the execution paused on the first line
- Add the test sources into the inspector: click the "Filesystem" on the left and then "Add folder to workspace".
- Browse to the folder with tests and add it.
- Open the file with the test to debug and set the breakpoint, continue the execution until it reaches the breakpoint
- Now you can step through your test, inspect variables, etc
Related links:
Truffle - Debugging unit tests
Truffle - Launching "truffle test" from JS code (debugging)
How can I debug a truffle JS unit test with vscode?
- 1,011
- 1
- 15
- 35
- 131
- 3
-
HINT: I'm using
CMD + Pto jump to file. At first not all files are loaded, usingdebuggerstatement in the code... – Mars Robertson Apr 04 '18 at 18:12
truffle-corehas been deprecated. Installtruffleinstead. Also the program path would now look like this:${workspaceFolder}\\node_modules/truffle/build/cli.bundled.js– Saeb Amini Jan 11 '19 at 01:36