We will see a bit of configuration from karma and an example of a working enviroment for testing and coverage.
This is presented as a solution with ECMA5. In order to go for ECMA6 I recommend look for babelify transformation.
For impatients you can find the repo here
The karma configuration we will be analyzing will be this one
In this case we need to have installed nodejs, npm, and karma, mocha, phantomjs and expect for assertion.
Defining Karma Reporters
We will define what we want from Karma, and thats going to be with this line:
So we are going to give a report on coverage and run spec too. So in order to do so we need some dependencies in package json those are:
Defining Karma Frameworks
Then we can say which frameworks we will be using to karma.
You can see that we are using mocha for runing those tests, and browserify to make a bundle on what we need to test.
Files to test.
What are we going to test?, we can define a regular expression to say where are the source files of our application and where are the tests.
Preprocess some files
We need to define what we will be running before processing all the data with karma.
In this case we are saying, execute browserify to bundle my source code then execute coverage.
Then we say execute browserify on test.
In this case you can specify some operations for those reports you defined before. You can add some customs and say how to do somethings to karma for those reports.
In this case we are saying that we want results in html, text, lcovonly. We are saying we will use Istanbul as an instrumenter to produce this coverage. lcov is the result the coverage, it is information formatted in a particular way so you can read from this lcov in order to produce a report in the way you need with different tools. So we can say that you can use other libraries that are not Istanbul and they may produce lcov information too.
As we have defined browserify early we may need to define how to make some transformations for our bundles.
So we are saying run brfs, this is a plugin that will inline the reading of files into bundles, and then istanbul will actually work with the coverage ignoring node modules and tests.
Defining your browser
You can define your browser for karma like this:
phantomjs2 is a headless browser that avoids having so much heavy work when running tests in browser.
you can see compatibility table for phantomjs2 in here
finally we run karma with this line:
rm -r coverage && karma start karma.local.conf.js
the results on this coverage are in my terminal are this ones:
the results on this coverage in my browser are:
we can explore those results a bit more and find the lines not covered
now we know how to run our testing with coverage in a headless browser. there are several reasons why testing is important, soon we will see a nice approach in this same project with continuous integration, github and for multiple platforms.
hope you enjoy this little sample, the repo with the code is here