[英]Detecting console.log() calls
我正在嘗試為調試方法編寫一個測試用例,該方法使用console.log()
將消息寫入JavaScript控制台。 測試必須檢查消息是否已成功寫入控制台。 我正在使用jQuery。
有沒有一種方法可以將鈎子連接到console.log()
或以其他方式檢查是否已將消息寫入控制台,或者是否有關於如何編寫測試用例的其他建議?
console.log
不會保留已記錄消息的記錄,也不會發出您可以偵聽的任何事件。 您的測試不可能直接驗證來自JavaScript的輸出。 相反,您的測試代碼將需要用模擬實現替換console.log
,該實現不會跟蹤日志消息,以便以后進行驗證。
模擬是大多數JavaScript測試框架支持的常見功能。 例如, Jest測試框架提供了一個jest.spyOn
函數 ,該函數將一個給定的方法替換為模擬實現,該模擬實現將每個調用的參數記錄在.mock
屬性中,然后.mock
原始實現。 每次測試之后,您可能需要調用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();
});
如果您不使用測試框架(可能應該使用),則可以自己創建一個簡單的模擬。
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;
}
}
因此,解決方案還不錯,但是如果您正在尋找功能強大的記錄器,請嘗試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 );
如果您使用的是茉莉花,那就太簡單了:
it('is my test', function () {
spyOn(console, 'log');
// do your stuff that should log something
expect(console.log).toHaveBeenCalledWith('something');
});
前往Jasmine文檔獲取更多信息。
只需將自己的函數附加到console.log。 在頁面上,所有內容加載完畢后,
在開始測試之前-
var originalLog = console.log;
console.log = function(msg){
alert('my .log hook received message - '+msg);
//add your logic here
}
運行測試后,如有必要-
console.log = originalLog
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.