如何在 Karma/Jasmine 中检查控制台日志?

gir*_*ffe 5 jasmine phantomjs karma-runner

假设我有这个功能我想测试:

var test = function () {
  console.log('words!');
};
Run Code Online (Sandbox Code Playgroud)

我会写这样的东西

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

但我不知道如何查看控制台日志,或者这是否可能。最好,我会在任何浏览器中执行此操作,或者至少是 PhantomJS。

Sla*_*nov 7

您可以在 console.log 函数上创建间谍。代码可能看起来像......

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

通过这个例子,你会知道你的 console.log 函数被调用了。这正是您需要知道的。您不想将记录的消息与预期值进行比较,仅仅因为您将单元测试不是您的代码,而是 window.console.log 函数本身,您没有编写;) 您可以调用“.and.callFake(function (){做点什么});”。在这种情况下,您将执行一些操作而不是实际的 console.log 调用,例如检查您的值。