简体   繁体   English

检测console.log()调用

[英]Detecting console.log() calls

I'm trying to write a test case for a debugging method that writes messages to the JavaScript console using console.log() . 我正在尝试为调试方法编写一个测试用例,该方法使用console.log()将消息写入JavaScript控制台。 The test has to check that the message has been successfully written to the console. 测试必须检查消息是否已成功写入控制台。 I'm using jQuery. 我正在使用jQuery。

Is there a way to attach a hook to console.log() or otherwise check that a message has been written to the console, or any other suggestions on how to write the test case? 有没有一种方法可以将钩子连接到console.log()或以其他方式检查是否已将消息写入控制台,或者是否有关于如何编写测试用例的其他建议?

console.log doesn't keep a record of messages that are logged, or emit any events that you could listen for. console.log不会保留已记录消息的记录,也不会发出您可以侦听的任何事件。 It's not possible for your tests to directly verify its output from JavaScript. 您的测试不可能直接验证来自JavaScript的输出。 Instead, your test code will need to replace console.log with a mock implementation that does keep track of log messages for later verification. 相反,您的测试代码将需要用模拟实现替换console.log ,该实现不会跟踪日志消息,以便以后进行验证。

Mocking is a common feature supported by most JavaScript test frameworks. 模拟是大多数JavaScript测试框架支持的常见功能。 For example, the Jest test framework provides a jest.spyOn function which replaces a given method with a mock implementation that records the arguments for each call in a .mock property before passing them on to the original implementation. 例如, Jest测试框架提供了一个jest.spyOn函数 ,该函数将一个给定的方法替换为模拟实现,该模拟实现将每个调用的参数记录.mock属性中,然后.mock原始实现。 After each test you may want to call jest.clearAllMocks() to reset the recorded argument lists for the next test, or use the equivalent clearMocks: true config option . 每次测试之后,您可能需要调用jest.clearAllMocks()来为下一次测试重置记录的参数列表,或者使用等效的clearMocks: true config选项

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();
});

If you're not using a test framework (you probably should), you can create a simple mock yourself. 如果您不使用测试框架(可能应该使用),则可以自己创建一个简单的模拟。

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;
  }
}

So not bad solutions, but if you're looking for a high powered logger try Paul Irish's log() 因此,解决方案还不错,但是如果您正在寻找功能强大的记录器,请尝试Paul Irish的log()

If that's too high powered, you can get by with something like this. 如果功率太高,您可以通过这样的方式来解决。

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 );
}

Usage 用法

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

http://jsfiddle.net/BeXdM/ http://jsfiddle.net/BeXdM/

If you're using Jasmine, it's dead simple: 如果您使用的是茉莉花,那就太简单了:

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

Head to Jasmine docs for more info. 前往Jasmine文档获取更多信息。

Just attach your own function to console.log. 只需将自己的函数附加到console.log。 On your page, after everything loads, 在页面上,所有内容加载完毕后,

Before starting tests - 在开始测试之前-


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

After running tests, if necessary - 运行测试后,如有必要-

console.log = originalLog

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM