检测console.log()调用

时间:2011-08-30 16:54:11

标签: javascript jquery tdd error-logging

我正在尝试编写一个调试方法的测试用例,该方法使用console.log()将消息写入JavaScript控制台。测试必须检查消息是否已成功写入控制台。我正在使用jQuery。

有没有办法将挂钩附加到console.log()或以其他方式检查是否已将消息写入控制台,或者有关如何编写测试用例的任何其他建议?

4 个答案:

答案 0 :(得分:17)

console.log不会记录已记录的消息,也不会发出您可以侦听的任何事件。您的测试无法直接验证JavaScript的输出。相反,您的测试代码需要将console.log替换为模拟实现,该实现会跟踪日志消息以供日后验证。

Mocking是大多数JavaScript测试框架支持的常见功能。例如,the Jest test framework provides a jest.spyOn function使用模拟实现替换给定方法,该模拟实现在将每个调用传递给原始实现之前记录每个调用in a .mock property的参数。每次测试后,您可能需要调用jest.clearAllMocks()重置下次测试的录制参数列表,或使用the equivalent clearMocks: true config option

function saySomething() {
  console.log("Hello World");
}
jest.spyOn(console, 'log');

test("saySomething says hello", () => {
  expect(console.log.mock.calls.length).toBe(0);
  saySomething();
  expect(console.log.mock.calls.length).toBe(1);
  expect(console.log.mock.calls[0][0]).toBe("Hello World");
});

afterEach(() => {
  jest.clearAllMocks();
});

如果你没有使用测试框架(你可能应该),你可以自己创建一个简单的模拟。

function saySomething() {
  console.log("Hello World");
}
function testSomething() {
  // Replace console.log with stub implementation.
  const originalLog = console.log;
  const calls = [];
  console.log = (...args) => {
    calls.push(args);
    originalLog(...args);
  };

  try {
    console.assert(calls.length == 0);
    saySomething();
    console.assert(calls.length == 1);
    console.assert(calls[0][0] == "Hello World");
  } catch (error) {
    console.error(error);
  } finally {
    // Restore original implementation after testing.
    console.log = originalLog;
  }
}

答案 1 :(得分:9)

所以解决方案也不错,但如果您正在寻找高功率记录器,请尝试Paul Irish的log()

如果功率过高,你就可以得到类似的东西。

var console = window.console,
    _log = console ? console.log : function(){};

_log.history = [];

console.log = function( ){
  _log.history.push.apply( _log.history, arguments );
  _log.apply( console, arguments );
}

用法

console.log('I','have','an','important','message');
//Use native one instead
_log.call( console, _log.history );

http://jsfiddle.net/BeXdM/

答案 2 :(得分:8)

如果你正在使用Jasmine,那就简单了:

it('is my test', function () {
    spyOn(console, 'log');
    // do your stuff that should log something
    expect(console.log).toHaveBeenCalledWith('something');
});

前往Jasmine docs获取更多信息。

答案 3 :(得分:5)

只需将自己的功能附加到console.log即可。 在您的页面上,加载完所有后,

在开始测试之前 -


var originalLog = console.log;
console.log = function(msg){
  alert('my .log hook received message - '+msg); 
  //add your logic here
}

运行测试后,如有必要 -

console.log = originalLog
相关问题