Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check for a console log in Karma/Jasmine?

Let's say I have this function I want to test:

var test = function () {
  console.log('words!');
};

I'd write something like this

define('test()', function () {
  it('prints "words!" to the screen', function() {
    test();
    expect(<browser logs>).toContain('words!'); // TODO
  }
}

But I don't know how to view the console logs or if this is even possible. Preferably, I'd do this in any browser, or at least PhantomJS.

like image 507
giraffe Avatar asked Mar 13 '17 17:03

giraffe


1 Answers

You may create the spy on console.log function. The code may look like ...

describe("log reporting", function () {    
  beforeEach(function(){
    spyOn(window.console, 'log');
  });
  it('should print log message to console', function(){
    test();
    expect(window.console.log).toHaveBeenCalled();
  })
});

With this example you would know your console.log function was called. This is exactly what you need to know. You don't want to compare logged message with expected value, simply because you would unit test not your code, but window.console.log function itself, which you didn't write ;) You may call ".and.callFake(function(){do something});". In this case you would do something instead of actual console.log call, for example check your value.

like image 85
Slava Ivanov Avatar answered Sep 28 '22 09:09

Slava Ivanov