Skip to main content

Getting started and working with Karma


Getting started and working with Karma

In this article, I will talk about Installing and working with Karma for code coverage
We will go step by step to get started using it.

Pre-requisite - You are familiar with Angular coding and writing unit test cases.

So let's get started!!

      1. You need to install karma-coverage
     a.   npm i karma-coverage
2.       Changes to karma.config (blue highlighted are changed/added ones and comments are in bold white underlined text)

3     module.exports = function (config) {
4.    config.set({
5.      basePath: '',
6.      frameworks: ['jasmine', '@angular-devkit/build-angular'],
     files: [
8          { pattern: "app/**/*.+(ts|html)" }  --- added to search for files to be tested.
9.    ],
10. 
11.    plugins: [
12.      require('karma-jasmine'),
13.      require('karma-chrome-launcher'),
14.      require('karma-jasmine-html-reporter'),
15.      require('karma-coverage-istanbul-reporter'),
16.      require('@angular-devkit/build-angular/plugins/karma'),
17.      'karma-coverage' –added to include plugin for karma-coverage
18.    ],
19.    client: {
20.      clearContext: false // leave Jasmine Spec Runner output visible in browser
21.    },
22. 
23.    – Karma uses Istanbul in back to generate and compile test reports
24.    coverageIstanbulReporter: {
25.      dir: require('path').join(__dirname, '../coverage'),
      reports: ['html', 'lcovonly', 'text-summary'], -- Type of report we need
26.      fixWebpackSourcePaths: true,
27.      includeAllSources: true, -- Will also include those files in report which doesn’t have corresponding spec file
28.     
29. 
30.thresholds: { -- here we can define the thresholds/limits in percent for a file to pass coverage, i.e. coverage is reported pass only if these limit values are meet.
31.        statements: 100,
32.        lines: 80,
33.        branches: 60,
34.        functions: 60
35.      }
36.    },
37.    port: 9876,
38.    colors: true,
39.    logLevel: config.LOG_INFO, -- we have option of LOG_DEBUG to include debug level logging i.e. when we debug in karma.
40. 
41.    autoWatch: true, -- refresh report on change in files
42.    browsers: ['Chrome'],
43.    includeAllSources: true, -- Will also include those files in report which doesn’t have corresponding spec file
44. 
45.    singleRun: false,
46.    concurrency: Infinity,
47.  });
48.};

3.       If classes in a different file are referenced in a component, which has a corresponding spec file the code coverage for those files will also be included to coverage report and the file will be shown in report with details.
4.       If there is no spec file and the class/file is not referenced anywhere then coverage for that file will not be evaluated, the will be dropped from the report.
5.       If report shows 100% coverage that means the code has a full coverage in spec file or there are no possible logic to be tested ie. Like if we have a model.ts with only property/var declared without conditions then the coverage report for that file will be 100%.
6.       To always run the coverage we can modify our angular.json file by including highlighted attribute to test section.
"test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "codeCoverage": true,

7.       The report can be found the folder setup for report in karma.config file, in our example this is root/coverage/html
8.       The file for report is index.html in folder from point 7 above.
9.       Running code coverage in test.
a.       ng test --code-coverage (if we haven’t configured for run coverage in every test from point 6 above)
b.      ng test (if we have configured as in point 6 above)

Reading the coverage report
Coverage criteria:
1.       Function coverage has each function (or subroutine) in the program been called?
2.       Statement coverage has each statement in the program been executed?
3.       Branch coverage has each branch (also called DD-path) of each control structure (such as in if and case statements) been executed? For example, given an if statement, have both the true and false branches been executed? Another way of saying this is, has every edge in the program been executed?
4.       Line coverage has each executable line in the source file been executed?
5.       For each case, the percentage represents executed code vs not-executed code, which equals each fraction in percent format (e.g: 50% branches, 1/2).
File report:
1.       'E' stands for 'else path not taken', which means that for the marked if/else statement, the 'if' path has been tested but not the 'else'.
2.       'I' stands for 'if path not taken', which is the opposite case: the 'if' hasn't been tested.
3.       The xN in left column is the amount of times that line has been executed.
4.       Not executed lines, or pieces of code, will be highlighted in red.

It also provides some colour codes:
1.       Pink: statements not covered.

2.       Orange: functions not covered.

3.       Yellow: branches not covered.



Comments

Popular posts from this blog

A dip into DeepSeek

  Introduction to DeepSeek  DeepSeek is a Chinese AI company founded in 2023 by Liang Wenfeng. It is located in Hangzhou, Zhejiang. DeepSeek has focused on open-source large language models. Within a very short time, the company has caught people's attention through its new models, DeepSeek-V3 and DeepSeek-R1, which could soon become the new benchmark to rival leading AI models from other tech companies. About DeepSeek DeepSeek's models are highly performing and efficient. DeepSeek stresses more on open-source development, therefore, models, and training facts about them are free to use and alter. Such practices helped DeepSeek grow by leaps and bounds and now it is one of the market leaders in the AI domain. DeepSeek's models have been developed under serious challenges from U.S. export bans on advanced hardware, notwithstanding such challenges, DeepSeek has been amazing. Comparison with ChatGPT, Microsoft Copilot, and Gemini Model Key Featur...

.Net 8 - A look for Technical Architect

 .NET 8, the latest Long-Term Support (LTS) release from Microsoft, arrived in November 2023.  As a technical architect, you're likely interested in what this means for your development and the applications you're building.  Performance Boost .NET 8 comes with significant performance improvements. Such as garbage collection optimizations and core library enhancements, your applications will see a noticeable speedup. This results in a better user experiences and improved scalability. Geared up with C# 12 .NET 8 introduces C# 12. C# 12 offers several new features that improve code readability and maintainability, such as global using and improved pattern matching. These features empower developers to write cleaner and more efficient code. Cross-Platform Development .NET 8 strengthens the cross platform capabilities of .Net. Whether you're targeting Windows, Linux, macOS, or mobile platforms, .NET 8 provides the tools and libraries you need to build robust applications. Expa...

Being AGILE

AGILE! many of us had heard of this or even following it, so what it is. Lets start with simple word explanation in English dictionary it says  "Able to move quickly and easily" . That's it, the methodology is all about moving quickly and easily. What is AGILE? Agile is a project management technique or you can say a open methodology, projects can be of any nature and field, it can be applied to almost any kind of project. In this article we will talk more about software development projects. Its a methodology Not a process, it's a philosophy or set of values Agile breaks down larger projects into small, manageable chunks called iterations. At the end of each iteration (which generally takes place over a consistent time interval) something of value is produced. Agile has different method implementation like XP (extreme programming), Scrum, Crystal, Kanban, RUP etc.read more methods here  So how we will move quickly and easily . By making small go...