javascript 检测 console.log() 调用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7246884/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Detecting console.log() calls
提问by JJJ
I'm trying to write a test case for a debugging method that writes messages to the JavaScript console using console.log()
. The test has to check that the message has been successfully written to the console. I'm using jQuery.
我正在尝试为调试方法编写测试用例,该方法使用console.log()
. 测试必须检查消息是否已成功写入控制台。我正在使用 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()
或以其他方式检查消息是否已写入控制台,或者有关如何编写测试用例的任何其他建议?
回答by Facebook Staff are Complicit
console.log
doesn't keep a record of messages that are logged, or emit any events that you could listen for. It's not possible for your tests to directly verify its output from JavaScript. Instead, your test code will need to replace console.log
with a mockimplementation that does keep track of log messages for later verification.
console.log
不会记录已记录的消息,也不会发出您可以侦听的任何事件。您的测试不可能直接验证其来自 JavaScript 的输出。相反,您的测试代码将需要替换console.log
为一个模拟实现,该实现会跟踪日志消息以供以后验证。
Mocking is a common feature supported by most JavaScript test frameworks. For example, the Jest test framework provides a jest.spyOn
functionwhich replaces a given method with a mock implementation that records the arguments for each call in a .mock
propertybefore passing them on to the original implementation. 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.
Mocking 是大多数 JavaScript 测试框架都支持的常见功能。例如,在玩笑测试框架提供了一个jest.spyOn
功能,它取代了模拟实现,记录每个调用的参数给定方法的.mock
属性将它们传递到原来实施前。每次测试后,您可能希望调用jest.clearAllMocks()
以重置下一次测试的记录参数列表,或使用等效的clearMocks: true
配置选项。
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;
}
}
回答by Drew
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 );
回答by mik01aj
If you're using Jasmine, it's dead simple:
如果您使用的是 Jasmine,那就太简单了:
it('is my test', function () {
spyOn(console, 'log');
// do your stuff that should log something
expect(console.log).toHaveBeenCalledWith('something');
});
Head to Jasmine docsfor more info.
前往Jasmine 文档了解更多信息。
回答by Amol Katdare
Just attach your own function to console.log. On your page, after everything loads,
只需将您自己的函数附加到 console.log。在您的页面上,加载完所有内容后,
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