Settingup environment for test driven development(TDD) of client side javascript using Mocha, Karma and Watchify

Saturday  /  08 April 2017  / 

Developing Javascript application is a breeze. It has no strict type checks (loose typing), vast libraries to use from, no need of setting up development environment, can run anywhere, and more and more. But things could get messy pretty soon if you are constantly deveolping it adding logics day by day.

Very soon, the application grows ugly and maintaining it becomes painful task. Here is a great tutorial on setting up client side javascript project using gulp.

Javascript Unit testing

There are multiple testing frameworks out there and I prefer Mocha and Chai as I feel its more expressive.

Below is a simple function to generate object with query string of given url,

And a simple test case for it,

You can run this test with Mocha with below command,

$ mocha --compilers js:babel-core/register

But client side javascript involves Dom. You could very well install jsdom-global to solve document dependencies in your functions and test them. Thats ok, but what if we want to test using real browsers & multiple devices?

Real browser testing using karma

Karma is a test runner which runs the test cases in real browsers and across devices. Sounds awesome doesn’t it? Setting it up is also straight forward which is very well explained in their main website.

After installing & configuring, you can install the browser launchers you need and update the config file.

Now run the command to start karma, It will open the configured browsers and execute the test cases in all.

$ ./node_modules/.bin/karma start karma.conf.js --log-level debug --single-run
Connect multiple devices & auto execute test cases when code changes

The cool part about Karma is that, you could start it and add any device to it and the test cases gets autmatically executed for that device. You can see below, I added my Android phone to the running test just by opening the url in my mobile browser.

Read JioMags

Set autoWatch: true in karma.config.js file to allow test cases execution whenever the files change. Also, you could debug the code by adding a line debugger to four function & open Developer tools in your browser to start debugger. Exciting right? Go ahead & try for yourself.

Have setup boilerplate in Git repo with some Gulp tasks to get you started.