giraffe
giraffe

Reputation: 811

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.

Upvotes: 6

Views: 12250

Answers (2)

Albert
Albert

Reputation: 39

You can used calls tracker and check its provided arguments.

var test = function () {
  console.log('Hello world')
}

describe('Evaluate console.log', ()=>{
  it('prints "Hello words" to the screen', ()=>{
    const logSpy = spyOn(console, 'log').and.callThrough() // call actual console.log() function
    test()
    expect(logSpy.calls.count()).toBe(1) // check how many time it get called
    expect(logSpy.calls.first().args.length).toBe(2) // check how many words
    expect(logSpy.calls.first().args[0]).toBe('Hello') // first args = first word
    expect(logSpy.calls.first().args[1]).toBe('world') // and so on....
  })
})

Hope it helps,

Upvotes: 0

Slava Ivanov
Slava Ivanov

Reputation: 6912

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.

Upvotes: 9

Related Questions