Feb 14, 2018

Visual Studio Code: Debugging ES6 Mocha tests with Babel

In my post, I explained how to test server side REST APIs in Node.js using Mocha, Sinon and Chai. I used ES6 test methods for this and Babel is used to execute it. As test methods are executed at development end, so NO need to transpile ES6 to ES5 first and then debug the converted files. You can directly debug ES6 code with Babel.

Environment

Node 8.11.3

NPM 5.6.0

mongoose 5.2.x

express: 4.16.0

mocha 5.2.0

babel-cli 6.26.3

babel-preset-es2015 6.24.1

Visual Studio Code 1.25.1

Before we get started, let us take a look at how we executed the test files in the post. The application includes both source code and test files. To differentiate, .test.js extension is used.

The following npm scripts is used to run tests


 "scripts": {
    "clean": "shx rm -rf dist",
    "test": "npm run clean && \"./node_modules/.bin/mocha\" --timeout 5000 --require babel-core/register \"./{,!(node_modules)/**/}*.test.js\""
}

It cleans dist folder then run mocha with babel and .test.js files ignoring node_modules folder.

In .babelrc file, es2015 preset is used


{
    "presets": ["es2015"],
    "plugins": [
      "add-module-exports"
    ]
  }

Launch configuration

Click Debug icon > Configure gear icon on top bar > Select debug environment: Node.

It will generate a launch.json

Now add following section in configurations


"configurations": [
        {
            "name": "Debug Tests",
            "type": "node",
            "request": "launch",
            "cwd": "${workspaceRoot}",
            "program": "${workspaceRoot}/node_modules/mocha/bin/_mocha",
            "args": [
             "./{,!(node_modules)/**/}*.test.js",
                "--require", "babel-core/register",
                "-u", "tdd",
                "--timeout", "999999",
                "--colors"
            ],
            "runtimeArgs": [
                "--nolazy"
            ],
            "sourceMaps": true
        }
    ]

in the Debug sidebar > Select Debug Tests in top drop-down > Press F5 or click green arrow to start debug session. That's it. You can put break-point and evaluate expression in watch window.

debug vscode MOCHA

Conclusion

In this post, we saw how easy is to use VSCode debugging with ES6 Mocha test using Babel. As ES6 syntax is more developer friendly, it makes dev life easier to debug it. If you have any question or suggestion, feel free to leave a comment below.

Enjoy VSCode !!