問題描述
有沒有辦法測試 console.log 整體 (Is there a way to test for console.log entires)
我目前正在嘗試為我的團隊擁有的應用程序實施端到端單元測試。該應用程序在網站上嵌入視頻內容並記錄播放器上發生的事件。
示例:當我們的 trackscript 服務器運行時,我們可以轉到 https://www.thrillist.com/ 當視頻正在播放時,我們可以監控播放器上發生的事件,例如靜音、快進、暫停等...並將它們記錄到控制台。
我們正在嘗試實施單元測試以檢查記錄在這些事件上的數據是否正在發生。
我們目前正在研究 BrowserStack 以檢查跨瀏覽器的兼容性,並可能使用諸如 nightwatch.js 之類的框架來編寫單元測試。
我的問題是,你可以編寫檢查控制台日誌的夜間測試嗎?
參考解法
方法 1:
Usually it's not recommended to unit test log messages: they are not part of the required behavior for a given piece of code, and should be able to change without breaking a bunch of tests.
However, if you really want to unit test log messages anyway, the recommended approach is the same as with anything you want to unit test: Wrap calls to the console messages in a separate class and use dependency injection to inject that class into your components. That way you can create spies, mocks, etc. for that dependency.
(by Michael Carneal、StriplingWarrior)