Automated JS unit testing in VS Code

Automated JS unit testing in VS Code

I love using VS Code, and i want to be more diligent about unit testing especially with JavaScript. There didn’t seem to be an obvious way to do this in VS Code, so I cobbled together a few resources that ended up working well. It does require you have node.js installed on your machine first, so get that then proceed.

By the way, for those of you familiar with unit testing this may seem remedial and possibly outdated. It’s new to me, and I don’t want to forget how I did this, so feel free to leave comments and contribute to me and other newcomers to JS unit testing what works for you and what you suggest should be done differently.

There are plenty of test suites and task runners, choose what works best for you. The key takeaway is we need a test suite and a task runner of some kind. For this I’m using QUnit and Karma.

With VS Code open to your project folder, open the terminal and run the following commands:

npm install karma --save-dev
npm install karma-qunit karma-phantomjs-launcher --save-dev
npm install -g karma-cli
npm install --save-dev qunitjs

Once those are done installing configure karma by running this command:

karma init karma.conf.js

Follow the prompts to configure how it will run. For automated testing ensure you answer “Yes” when it asks if you want to re-run tests when a file changes. It’s not like WebStorm where it waits a few seconds, sees no activity, auto-saves then runs the tests, but it will autorun if you save the file. Once finished run this command to launch the task runner:

karma start

That’s it, now when you write your JS tests they will autorun and display in the terminal whenever you save changes. Of course, you can also open the browser to your html file you make when building your tests, such as with QUnit. There are other browsers you can use as well, including PhantomJS for headless browser testing. Let me know what works for you!

Comments are closed.