How to exclude Folder (components) for unit testing in Angular 4 using Karma config?
Asked Answered
P

2

8

I am using angular cli version 1.4.5 and below is the karma.conf.ts file

module.exports = function (config) {
  config.set({
  basePath: '',
  exclude: [
     "src/app/components/panel/panel.component.spec.ts",
     "src/app/components/accordion/accordion.component.spec.ts"
   ],
   frameworks: ['jasmine', '@angular/cli'],
   plugins: [
     require('karma-jasmine'),
     require('karma-chrome-launcher'),
     require('karma-jasmine-html-reporter'),
     require('karma-coverage-istanbul-reporter'),
     require('@angular/cli/plugins/karma')
   ],
   client:{
     clearContext: false 
   },
   coverageIstanbulReporter: {
     reports: [ 'html', 'lcovonly' ],
     fixWebpackSourcePaths: true
   },
   angularCli: {
     environment: 'dev'
   },
   reporters: ['progress', 'kjhtml'],
   port: 9876,
   colors: true,
   logLevel: config.DEBUG,
   autoWatch: true,
   browsers: ['Chrome'],
   singleRun: false
 });
};

and I even added the exclude in the tsconfig.spec.json file to exclude to pick those files for test.

{
 .....,
 "include": [
 "**/*.spec.ts",
 "**/*.d.ts"
 ],
 "exclude": [
     "app/components/panel/panel.component.spec.ts",
     "app/components/accordion/accordion.component.spec.ts"
 ]
}

is that am missing something to add for exclusion ?

Pointillism answered 6/2, 2018 at 7:20 Comment(0)
P
6

Change the config in the src/test.ts.

const context = require.context('./', true, /\.spec\.ts$/);

https://github.com/angular/angular-cli/issues/9026#issuecomment-354475734

Pentstemon answered 14/5, 2018 at 9:29 Comment(1)
Works for Angular 7 too.Lobo
D
1

Updated February 2024

For Angular-CLI 10 & latest, there is really no need to exclude them in your karma.conf.js as that won't work without further re-configurations.

Easiest way is to navigate to your angular.json which contains the configurations. If it's not there already, add codeCoverageExclude: array & include the files & folders to be excluded during karma build on ng test.

To do so, add codeCoverageExclude property which accepts an array of files to be excluded from code coverage as below.

"test": {
  "builder": "@angular-devkit/build-angular:karma",
  "options": {
    ...
    "karmaConfig": "karma.conf.js",
    ...
    "codeCoverageExclude": [
       "src/app/components/panel/**",
       "src/components/accordion/**",
       "src/app/*.ts"
     ],

To examine the result, run ng test --code-coverage and navigate to the newly created coverage folder of your app root directory and doudle-click to open the index.html file & see the pdf report in your browser.

PS: For smooth testing, Angular's Karma & Jasmine are configured by default to expect Google Chrome installed in your machine for tests to complete.

  • Happy testing & May Code be with you!
Devotional answered 20/2, 2024 at 9:28 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.