Thursday, April 27, 2017

Debug my Karma

I've just started getting my fingers in Angular. I've worked briefly with AngularJS in the past.
Although, I'm doubtless - you know the saying: testing is doubting 😁
I've always started looking at new framework with unit testing in mind. In this post, I'll use Google team term Angular stands for post 2.0, in there I'll use the latest release ie: 4.0.

When writing test, it is sometimes useful to debug the test using devtools (come on... no console log, vintage time is over πŸ‘ΎπŸ‘ΎπŸ‘Ύ). Let's see how to debug your test suite with Karma... It all depends on how your started your project: Let's see how to get a comfortable environment...

With angular2-webpack-starter

Follow README instructions:

git clone --depth 1
cd angular2-webpack-starter
npm install
npm test

When you run it you can see a blinking browser opening, running the test and closing. To be able to debug, open package.json and add:

  "name": "angular2-webpack-starter",
  "scripts": {
  "test:debug": "karma start --no-single-run --browsers Chrome",

Now just run npm run test:debug. Karma is now in single mode therefore Chrome stays opened!
Easy to debug simply cmd + alt + I to open devtools.
Also, note that the coverage report is ran and now visible!

With angular-cli project

Let's open a shell, you'll need node 6.5+ / npm 3+, install angular-cli globally:

npm install -g @angular/cli

Create a project with angular cli and run the test:

ng new ngx-unit-test
cd ngx-unit-test
ng test

NOTE: npm test is an alias to ng test (as most projects nowadays use npm script. Very handy as you don't need to globally install ng-cli!)

ng test will bring chrome as per default. Easy to debug simply cmd + alt + I to open devtools. Open your favourite editor, change the code. The tests are re-run. Easy-peasy, not much to do. What about if you want to run the coverage tool?
From angular-cli wiki:

ng test --code-coverage --single-run

karma.conf.js the source of truth

In the end, it all boils down to karma.conf.js configuration file. Wether by default you're running continuously in watch mode (dev friendly) or your test run with PhantomJS (CI/CD friendly), this is up to Karma configuration. It is however always good to have a build command to override and offer dev and CI friendly build.

Happy coding! Happy testing!