The level of logging by karma can be changed in the karma.conf.js file.

Go to karma.conf.js and add/change the property logLevel to config.LOG_DISABLE if you don't want to see any logs or config.LOG_ERROR if you want to only see the errors. Like this:

module.exports = function (config) {
  config.set({
    ...,
    logLevel: config.LOG_ERROR,
    ...,
  })
}

If you are running karma from the command line you can append --log-level debug to the command for the same effect.

Answer from Tom on Stack Overflow
🌐
GitHub
github.com › angular › angular-cli › issues › 9757
[Documentation Request] ng test --log-level options · Issue #9757 · angular/angular-cli
February 23, 2018 - What would like to see implemented + what did you expect to see: The values available for the --log-level option · 👍React with 👍5jdjd1118, mradcliffe, AryanJ-NYC, kthy and p2501dev ... area: @angular-devkit/build-angulararea: docsRelated to the documentationRelated to the documentation
Author   DinoSourcesRex
Discussions

angular - Debug Tests in NG Test - Stack Overflow
I am using Angular CLI and VSCode but none of my breakpoints in my spec files seem to be getting hit when I run ng test? Do I need to do some config? More on stackoverflow.com
🌐 stackoverflow.com
July 13, 2018
ng test logging
Is it possible to output · ng test --watch=false --build=false More on github.com
🌐 github.com
7
June 29, 2016
angularjs - is it possible in angular to set the debug log level at runtime? - Stack Overflow
If you don't like to type into the console, you could avoid the global cfg and use javascript bookmarks (or elements on your website) to change the log level. ... 'use strict'; app .config(['$logProvider', function($logProvider ){ var $cookies; angular.injector(['ngCookies']).invoke(['$cookies', ... More on stackoverflow.com
🌐 stackoverflow.com
Angular CLI is up and running event ng test --watch false after finishing
-- ng test --watch false can't be executed 2nd time without warnings due to stale angular-cli ... $ ng test --browsers PhantomJS --watch false --log-level debug is successful for the first time, but 2nd invocation causes warnings: WARNING in ./~/@angular/core/src/linker/system_js_ng_module... More on github.com
🌐 github.com
2
October 8, 2016
🌐
npm
npmjs.com › package › @ng-lv › logging
@ng-lv/logging - npm
LogManager : log.logmanager registered Logger : log.map set log level : log.logmanager.setCurrentLogLevel(4, ['c1','c2']) export enum LogLevel { Nothing, // 0 Verbose, // 1 Debug, // 2 Info, // 3 Warning, // 4 Error, // 5 Critical // 6 } Run ng serve for a dev server.
      » npm install @ng-lv/logging
    
Published   May 12, 2017
Version   1.0.2
🌐
npm
npmjs.com › package › ngx-logger
ngx-logger - npm
April 13, 2023 - import { LoggerModule, NgxLoggerLevel } from "ngx-logger"; // HttpClientModule is only needed if you want to log on server or if you want to inspect sourcemaps import { HttpClientModule } from "@angular/common/http"; The only remaining part is to list the imported module in your application module, passing in a config to initialize the logger. @NgModule({ declarations: [AppComponent, ...], imports: [ // HttpClientModule is only needed if you want to log on server or if you want to inspect sourcemaps HttpClientModule, LoggerModule.forRoot({ serverLoggingUrl: '/api/logs', level: NgxLoggerLevel.DEBUG, serverLogLevel: NgxLoggerLevel.ERROR }), ...
      » npm install ngx-logger
    
Published   Apr 13, 2023
Version   5.0.12
Top answer
1 of 6
71

Update for Angular version 9

The source files have been moved but you can still debug this way if you do the following steps

  • In devtools, select the sources tab
  • Press CTRL + P
  • Type in the name of the file you want to debug

Valid for versions below 9

The other answers are completely valid answers but having been using Angular for around 18 months now I tend to do it in the browser - chrome tools!

Run ng test then f12 and find the spec file via the webpack context. Add a breakpoint(s) and refresh and it will hit said breakpoints. As per screenshot

2 of 6
47

This is what worked for me with:

  • Angular 9.0.6 + Visual Studio Code 1.43.2
  • Angular 8.2.13 + Visual Studio Code 1.39.2
  • Angular 7, Angular CLI 1.0.* and Chrome on Windows 7.

Change configuration files

In your project root directory open karma.conf.js. Right after singleRun: false add , followed by this section:

    customLaunchers: {
      ChromeDebug: {
        base: 'Chrome',
        flags: [ '--remote-debugging-port=9333' ]
      }
    }

Add configuration to .vscode/launch.json.

  • For versions 8.* - 9.* (note "pathMapping section!):

    {
      "type": "chrome",
      "request": "attach",
      "name": "Unit tests",
      "address": "localhost",
      "port": 9333,
      "sourceMaps": true,
      "webRoot": "${workspaceFolder}",
      "pathMapping": {
        "/_karma_webpack_": "${workspaceFolder}"
      }
    },
    
  • For version 7.*:

    {
      "type": "chrome",
      "request": "attach",
      "name": "Unit tests",
      "address": "localhost",
      "port": 9333,
      "sourceMaps": true,
      "webRoot": "${workspaceFolder}"
    },
    

Start debugging

  1. Run ng test --browsers ChromeDebug

  2. Wait for Chrome browser to start. You will see something like this in command line:

    01 06 2017 16:07:29.276:INFO [launcher]: Launching browser ChromeDebug with unlimited concurrency
    
  3. Set the breakpoint in one of your .spec.ts files.

  4. In Visual Studio Code choose Unit tests debug configuration and hit F5 ("Start Debugging" button).

  5. Press Shift+Ctrl+F5 or refresh the Chrome window to rerun the tests and hit the breakpoint.


For convenience

You can also modify your package.json and add a new script:

"test-debug": "ng test --browsers ChromeDebug",

Then next time you want to start ng test with debugging just run:

npm run test-debug

References:

  • Debugging Jasmine Unit tests running with Karma runner in VS Code
  • Debugging Karma tests with VSCode
  • Angular CLI 8.1.3 Debug Unit Tests configuration - Unverified breakpoint
  • microsoft/vscode-recipes - Chrome Debugging with Angular CLI
🌐
GitHub
github.com › angular › angular-cli › issues › 1246
ng test logging · Issue #1246 · angular/angular-cli
June 29, 2016 - Hi Guys, Is it possible to output ng test --watch=false --build=false to external file? so that I can parse the file in TeamCity and fail the build. I tried below ng test --watch=false --build=false > log.txt but it only write True in it...
Author   kamran-pervaiz
🌐
Testing-angular
testing-angular.com › debugging-tests
Debugging tests – Testing Angular
February 17, 2021 - Write debug output to the console using console.log, console.debug and friends.
🌐
CodeMag
codemag.com › article › 1711021 › Logging-in-Angular-Applications
Angular: Adding Logging in Angular Applications
October 27, 2017 - The shouldLog() method determines if logging should occur based on the level property set in the LogService class. This service is created as a singleton by Angular, so once this level property is set, it remains that value until you change it in your application.
Find elsewhere
🌐
Medium
thesiddharthraghuvanshi.medium.com › logging-in-angular-application-angular-logger-service-8bc90096dcf6
Logging in Angular Application | Angular Logger Service | by Siddharth Raghuvanshi | Medium
January 4, 2022 - Levels in logs are the senses to code, like human body have sense of Sight, Sound, Smell, Taste, and Touch similarly loggers have levels as None, Info, Debug, Warn, Error. Let’s define them in logelevel.model.ts file
🌐
Ng-log
ng-log.github.io › ng-log › 0.8.0 › logging
Logging - ng-log
Therefore, the macros defined in this header file can be used by low-level memory allocation and synchronization code. Please check src/ng-log/raw_logging.h for detail. PLOG() and PLOG_IF() and PCHECK() behave exactly like their LOG* and CHECK equivalents with the addition that they append a description of the current state of errno to their output lines. E.g. PCHECK(write(1, nullptr, 2) >= 0) << "Write nullptr failed"; This check fails with the following error message. F0825 185142 test.cc:22] Check failed: write(1, nullptr, 2) >= 0 Write nullptr failed: Bad address [14]
Top answer
1 of 3
1

The short answer for this is: no, not really.

Once your application hass been configured through your .config() block, no further configuration can take place after the application has bootstrapped.

This is due to the way providers work; they're only available at configuration time. There might be a way to force the configuration, and then manually re-inject the new $log service into all of your controllers, but if there is a way to do that, I'm not sure how.

2 of 3
1

I've decorated $log.debug(...) to change the loglevel at runtime.

Looking at Enhancing AngularJS Logging using Decorators, I got the idea for the following code snippet:

(function () {
    var KEY = "debugEnabled";

    angular.module("service.config", [])
        .config(function ($provide, $logProvider) {
            // AngularJS has debug enabled by default, but just to be sure...
            $logProvider.debugEnabled(true);

            // Disabling localStorageDebug (if not set)
            if (localStorage.getItem(KEY) === null) {
                localStorage.setItem(KEY, "false");
            }

            // add a check for localStorageDebug before actually calling $log.debug(...)
            $provide.decorator('$log', function ($delegate) {
                var debugFunction = $delegate.debug;

                $delegate.debug = function () {
                    if (localStorage.getItem(KEY) !== "false") {
                        debugFunction.apply(undefined, arguments)
                    }
                };

                return $delegate;
            });
        })
        .service("ConfigService", function ($log) {
            this.debugEnabled = function (flag) {
                $log.info("Setting debugEnabled to " + flag);
                localStorage.setItem(KEY, flag.toString());
            }
        });
})();

// exposing ConfigService to global scope (be aware of possible clashes!),
// therefore making it easily accessible from the console
var cfg;
window.onload = function () {
    cfg = angular.element(document.body).injector().get("ConfigService");
};

The decorator only forwards calls to $log.debug if debugEnabled is set to true in your local storage - the value can be changed through the ConfigService service.

Now you can just call ConfigService#debugEnabled with the value you've loaded from your server to change the loglevel.

Thanks to the last four lines, you can also simply call cfg.debugEnabled(true) on your console to enable debug mode at runtime.

If you don't like to type into the console, you could avoid the global cfg and use javascript bookmarks (or elements on your website) to change the log level.

🌐
Bradoncode
bradoncode.com › blog › 2015 › 06 › 08 › ngmock-fundamentals-log
Unit Testing $log in AngularJS - ngMock Fundamentals
June 8, 2015 - describe('logs with debugging disabled', function () { beforeEach(module(function($logProvider) { // We can configure the debugging level (the default is true) $logProvider.debugEnabled(false); })); beforeEach(inject(function(_$controller_, _$log_) { $controller = _$controller_; $log = _$log_; $scope = {}; })); it('should not write to log when calling sum', function() { var productsController = $controller('CalculatorController', { $scope: $scope }); $scope.x = 1; $scope.y = 2; $scope.sum(); expect($log.assertEmpty).not.toThrow(); }); }); Full code example of the tests used in this post via a Github Gist. ... Bradley Braithwaite is a software engineer who works for search engine start-ups. He is a published author at pluralsight.com. He writes about software development practices, JavaScript, AngularJS and Node.js via his website bradoncode.com.
🌐
DEV Community
dev.to › alisaduncan › how-to-level-up-your-angular-unit-testing-game-13-7a1
How To Level Up Your Angular Unit Testing Game (1/3) - DEV Community
January 21, 2019 - Tips to run Angular unit tests and customize your test tooling. Tagged with testing, angular, tips, webdev.
🌐
Jvandemo
jvandemo.com › how-to-access-angular-log-debug-messages-from-within-karma
How to access Angular $log debug messages from within Karma
August 24, 2022 - // level of logging, possible values: // config.LOG_DISABLE // config.LOG_ERROR // config.LOG_WARN // config.LOG_INFO // config.LOG_DEBUG logLevel: config.LOG_DEBUG · does NOT make the $log.debug() calls magically appear in your Karma log output, as this setting only affects Karma internally, not your Angular $logProvider.
🌐
GitHub
github.com › angular › angular-cli › issues › 2582
Angular CLI is up and running event ng test --watch false after finishing · Issue #2582 · angular/angular-cli
October 8, 2016 - $ ng test --browsers PhantomJS --watch false --log-level debug · Windows 7, 8 or 10. Linux (which distribution). Mac OSX (Yosemite? El Capitan?) Linux 3.10 x86_64 · Please run ng --version. If there's nothing outputted, please run in a Terminal: node --version and paste the result here: angular-cli: 1.0.0-beta.16 node: 6.7.0 os: linux x64
Author   pranasblk
🌐
AngularJS
docs.angularjs.org › api › ng › service › $log
AngularJS
AngularJS is what HTML would have been, had it been designed for building web-apps. Declarative templates with data-binding, MVC, dependency injection and great testability story all implemented with pure client-side JavaScript!
🌐
npm
npmjs.com › package › ng-logger
ng-logger - npm
January 4, 2017 - import { Component, OnInit } from '@angular/core'; import { LoggerService } from 'ng-logger'; import { environment } from '../environments/environment'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { title = 'MyApp'; constructor( private log: LoggerService) { } ngOnInit() { // set the configuration directly this.log.logLevel = 'DEBUG'; this.log. // ..OR import the log level from your environment config (ng-cli for example) if (environment.logger) { this.log.logLevel = environment.logger
      » npm install ng-logger
    
Published   Jan 04, 2017
Version   1.1.0
Author   Ralph Capasso
🌐
Angular
v17.angular.io › cli › test
ng test
Angular is a platform for building mobile and desktop web applications. Join the community of millions of developers who build compelling user interfaces with Angular.
🌐
SentinelOne
sentinelone.com › blog › getting-started-angular-logging
Getting Started Quickly With Angular Logging | Scalyr
October 27, 2022 - We’ll add a new Angular component that has several buttons, and these buttons will trigger logging at the console at different levels.