DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

SBOMs are essential to circumventing software supply chain attacks, and they provide visibility into various software components.

Related

  • Mock the File System
  • How to Banish Anxiety, Lower MTTR, and Stay on Budget During Incident Response
  • Driving DevOps With Smart, Scalable Testing
  • Unit Testing Large Codebases: Principles, Practices, and C++ Examples

Trending

  • *You* Can Shape Trend Reports: Join DZone's Data Engineering Research
  • Docker Model Runner: Running AI Models Locally Made Simple
  • From Java 8 to Java 21: How the Evolution Changed My Developer Workflow
  • How Predictive Analytics Became a Key Enabler for the Future of QA
  1. DZone
  2. Coding
  3. Frameworks
  4. Code Coverage of Jasmine Tests using Istanbul and Karma

Code Coverage of Jasmine Tests using Istanbul and Karma

By 
Ariya Hidayat user avatar
Ariya Hidayat
·
Oct. 08, 13 · Interview
Likes (0)
Comment
Save
Tweet
Share
48.9K Views

Join the DZone community and get the full member experience.

Join For Free

for modern web application development, having dozens of unit tests is not enough anymore. the actual code coverage of those tests would reveal if the application is thoroughly stressed or not. for tests written using the famous jasmine test library, an easy way to have the coverage report is via istanbul and karma .

for this example, let’s assume that we have a simple library sqrt.js which contains an alternative implementation of math.sqrt . note also how it will throw an exception instead of returning nan for an invalid input.

var my = {
  sqrt: function(x) {
    if (x < 0) throw new error("sqrt can't work on negative number");
      return math.exp(math.log(x)/2);
  }
};

using jasmine placed under test/lib/jasmine-1.3.1 , we can craft a test runner that includes the following spec:

describe("sqrt", function() {
  it("should compute the square root of 4 as 2", function() {
    expect(my.sqrt(4)).toequal(2);
  });
});

opening the spec runner in a web browser will give the expected outcome:

jasmine_runner

so far so good. now let's see how the code coverage of our test setup can be measured.

the first order of business is to install karma . if you are not familiar with karma, it is basically a test runner which can launch and connect to a specific set of web browsers, run your tests, and then gather the report. using node.js, what we need to do is:

npm install karma karma-coverage

before launching karma, we need to specify its configuration . it could be as simple as the following my.conf.js (most entries are self-explained). note that the tests are executed using phantomjs for simplicity, it is however quite trivial to add other web browsers such as chrome and firefox.

module.exports = function(config) {
  config.set({
    basepath: '',
    frameworks: ['jasmine'],
    files: [
      '*.js',
      'test/spec/*.js'
    ],
    browsers: ['phantomjs'],
    singlerun: true,
    reporters: ['progress', 'coverage'],
    preprocessors: { '*.js': ['coverage'] }
  });
};

running the tests, as well as performing code coverage at the same time, can be triggered via:

node_modules/.bin/karma start my.conf.js

which will dump the output like:

info [karma]: karma v0.10.2 server started at http://localhost:9876/
info [launcher]: starting browser phantomjs
info [phantomjs 1.9.2 (linux)]: connected on socket n9ndnhj0np92ntspgx-x
phantomjs 1.9.2 (linux): executed 1 of 1 success (0.029 secs / 0.003 secs)

as expected (from the previous manual invocation of the spec runner), the test passed just fine. however, the most particular interesting piece here is the code coverage report, it is stored (in the default location) under the subdirectory coverage . open the report in your favorite browser and there you'll find the coverage analysis report.

branch_uncovered

behind the scene, karma is using istanbul , a comprehensive javascript code coverage tool (read also my previous blog post on javascript code coverage with istanbul ). istanbul parses the source file, in this example sqrt.js , using esprima and then adds some extra instrumentation which will be used to gather the execution statistics. the above report that you see is one of the possible outputs, istanbul can also generate lcov report which is suitable for many continuous integration systems (jenkins, teamcity, etc). an extensive analysis of the coverage data should also prevent any future coverage regression, check out my other post hard thresholds on javascript code coverage .

one important thing about code coverage is branch coverage . if you pay attention carefully, our test above is still not exercising the situation where the input to my.sqrt is negative. there is a big "i" marking in the third-line of the code, this is istanbul telling us that the if branch is not taken at all (for the else branch, it will be an "e" marker). once this missing branch is noticed, improving the situation is as easy as adding one more test to the spec:

it("should throw an exception if given a negative number", function() {
  expect(function(){ my.sqrt(-1); }).
    tothrow(new error("sqrt can't work on negative number"));
});

once the test is executed again, the code coverage report looks way better and everyone is happy.

full_coverage

if you have some difficulties following the above step-by-step instructions, take a look at a git repository i have prepared: github.com/ariya/coverage-jasmine-istanbul-karma . feel free to play with it and customize it to suit your workflow!



Code coverage unit test Jasmine (JavaScript testing framework)

Published at DZone with permission of Ariya Hidayat, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Mock the File System
  • How to Banish Anxiety, Lower MTTR, and Stay on Budget During Incident Response
  • Driving DevOps With Smart, Scalable Testing
  • Unit Testing Large Codebases: Principles, Practices, and C++ Examples

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • [email protected]

Let's be friends: