From c5028a8576080477d0e71f7fb2dd3819fc4c4301 Mon Sep 17 00:00:00 2001 From: Stein Magnus Jodal Date: Fri, 20 Jun 2014 11:14:49 +0200 Subject: [PATCH] js: Fix console setup, allow mocking of the console --- docs/api/js.rst | 4 ++++ js/src/mopidy.js | 26 +++++++++++++++----------- 2 files changed, 19 insertions(+), 11 deletions(-) diff --git a/docs/api/js.rst b/docs/api/js.rst index ff333992..372e7f4e 100644 --- a/docs/api/js.rst +++ b/docs/api/js.rst @@ -138,6 +138,10 @@ When creating an instance, you can specify the following settings: .. versionadded:: 0.19 (Mopidy.js 0.4) +``console`` + If set, this object will be used to log errors from Mopidy.js. This is + mostly useful for testing Mopidy.js. + ``webSocket`` An existing WebSocket object to be used instead of creating a new WebSocket. Defaults to undefined. diff --git a/js/src/mopidy.js b/js/src/mopidy.js index 42762807..b5dd13f5 100644 --- a/js/src/mopidy.js +++ b/js/src/mopidy.js @@ -9,8 +9,8 @@ function Mopidy(settings) { return new Mopidy(settings); } + this._console = this._getConsole(settings || {}); this._settings = this._configure(settings || {}); - this._console = this._getConsole(); this._backoffDelay = this._settings.backoffDelayMin; this._pendingRequests = {}; @@ -40,6 +40,20 @@ Mopidy.ServerError.prototype.constructor = Mopidy.ServerError; Mopidy.WebSocket = websocket.Client; +Mopidy.prototype._getConsole = function (settings) { + if (typeof settings.console !== "undefined") { + return settings.console; + } + + var con = typeof console !== "undefined" && console || {}; + + con.log = con.log || function () {}; + con.warn = con.warn || function () {}; + con.error = con.error || function () {}; + + return con; +}; + Mopidy.prototype._configure = function (settings) { var currentHost = (typeof document !== "undefined" && document.location.host) || "localhost"; @@ -59,16 +73,6 @@ Mopidy.prototype._configure = function (settings) { return settings; }; -Mopidy.prototype._getConsole = function () { - var console = typeof console !== "undefined" && console || {}; - - console.log = console.log || function () {}; - console.warn = console.warn || function () {}; - console.error = console.error || function () {}; - - return console; -}; - Mopidy.prototype._delegateEvents = function () { // Remove existing event handlers this.off("websocket:close");