diff --git a/README.md b/README.md index 73586d9..8fbfdd4 100644 --- a/README.md +++ b/README.md @@ -120,7 +120,7 @@ server in order to test your applications: ```javascript var $websocketBackend; - beforeEach(angular.mock.module('ngWebSocket', 'ngWebSocketMock'); + beforeEach(angular.mock.module('ngWebSocket', 'ngWebSocketMock')); beforeEach(inject(function (_$websocketBackend_) { $websocketBackend = _$websocketBackend_; @@ -137,8 +137,10 @@ name | arguments | description -------------------------------|------------|----------------------------------- flush | | Executes all pending requests expectConnect | url:String | Specify the url of an expected WebSocket connection -expectClose | | Expect "close" to be called on the WebSocket +expectClose | url:String | Expect "close" to be called on the WebSocket expectSend | msg:String | Expectation of send to be called, with required message +fakeClose | url:String | Used to fake close a socket and test corresponding close handlers +fakeMessage | url:String, data:object | Used to fake a backend initialized send action, which can be handled in onMessage verifyNoOutstandingExpectation | | Makes sure all expectations have been satisfied, should be called in afterEach verifyNoOutstandingRequest | | Makes sure no requests are pending, should be called in afterEach diff --git a/dist/angular-websocket-mock.js b/dist/angular-websocket-mock.js index 21bb08a..222c002 100644 --- a/dist/angular-websocket-mock.js +++ b/dist/angular-websocket-mock.js @@ -1,8 +1,8 @@ (function (global, factory) { if (typeof define === "function" && define.amd) { - define(['module', 'angular'], factory); + define(["module", "angular"], factory); } else if (typeof exports !== "undefined") { - factory(module, require('angular')); + factory(module, require("angular")); } else { var mod = { exports: {} @@ -11,7 +11,7 @@ global.angularWebsocketMock = mod.exports; } })(this, function (module, _angular) { - 'use strict'; + "use strict"; var _angular2 = _interopRequireDefault(_angular); @@ -28,11 +28,19 @@ var pendingCloses = []; var sendQueue = []; var pendingSends = []; + var pendingMessages = []; var mock = false; + var existingMocks = {}; function $MockWebSocket(url, protocols) { + this.url = url; this.protocols = protocols; this.ssl = /(wss)/i.test(this.url); + if (!existingMocks[url]) { + existingMocks[url] = [this]; + } else { + existingMocks[url].push(this); + } } $MockWebSocket.prototype.send = function (msg) { @@ -45,6 +53,19 @@ } }; + this.fakeClose = function (url, code) { + closeQueue.push(url); + if (existingMocks[url]) { + existingMocks[url].map(function (mockSocket) { + mockSocket.close(code); + }); + } + }; + + this.fakeMessage = function (url, data) { + pendingMessages.push({ url: url, data: data }); + }; + this.mock = function () { mock = true; }; @@ -57,8 +78,8 @@ return connectQueue.indexOf(url) > -1; }; - $MockWebSocket.prototype.close = function () { - pendingCloses.push(true); + $MockWebSocket.prototype.close = function (code) { + pendingCloses.push({ url: this.url, code: code ? code : 1000 }); }; function createWebSocketBackend(url, protocols) { @@ -76,19 +97,61 @@ this.create = createWebSocketBackend; this.createWebSocketBackend = createWebSocketBackend; + function callOpenCallbacks(url) { + existingMocks[url].map(function (socketMock) { + if (socketMock.onopen && typeof socketMock.onopen === "function") { + socketMock.onopen(); + } + }); + } + + function callCloseCallbacks(url, code) { + existingMocks[url].map(function (socketMock) { + if (socketMock.onclose && typeof socketMock.onclose === "function") { + socketMock.onclose({ code: code }); + } + }); + } + + function callMessageCallbacks(url, data) { + if (existingMocks[url]) { + existingMocks[url].map(function (socketMock) { + if (socketMock.onmessage && typeof socketMock.onmessage === "function") { + socketMock.onmessage({ data: JSON.stringify(data) }); + } + }); + } + } + + function setReadyState(url, state) { + if (existingMocks[url]) { + existingMocks[url].map(function (socketMock) { + socketMock.readyState = state; + }); + } + } + this.flush = function () { var url, msg, config; while (url = pendingConnects.shift()) { var i = connectQueue.indexOf(url); if (i > -1) { connectQueue.splice(i, 1); + callOpenCallbacks(url); + setReadyState(url, 1); } // if (config && config.url) { // } } - while (pendingCloses.shift()) { - closeQueue.shift(); + var pendingClose; + while (pendingClose = pendingCloses.shift()) { + var i = closeQueue.indexOf(pendingClose.url); + if (i > -1) { + closeQueue.splice(i, 1); + callCloseCallbacks(pendingClose.url, pendingClose.code); + setReadyState(pendingClose.url, 3); + } } while (msg = pendingSends.shift()) { @@ -103,6 +166,10 @@ sendQueue.splice(j, 1); } } + + while (msg = pendingMessages.shift()) { + callMessageCallbacks(msg.url, msg.data); + } }; this.expectConnect = function (url, protocols) { @@ -110,8 +177,8 @@ // connectQueue.push({url: url, protocols: protocols}); }; - this.expectClose = function () { - closeQueue.push(true); + this.expectClose = function (url) { + closeQueue.push(url); }; this.expectSend = function (msg) { diff --git a/dist/angular-websocket.js b/dist/angular-websocket.js index db99c8e..54ab2cf 100644 --- a/dist/angular-websocket.js +++ b/dist/angular-websocket.js @@ -25,12 +25,6 @@ }; } - var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { - return typeof obj; - } : function (obj) { - return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; - }; - var Socket; if (typeof window === 'undefined') { @@ -148,6 +142,13 @@ }; $WebSocket.prototype._connect = function _connect(force) { + if (this.socket) { + this.socket.onmessage = null; + this.socket.onopen = null; + this.socket.onerror = null; + this.socket.onclose = null; + this.socket.close(); + } if (force || !this.socket || this.socket.readyState !== this._readyStateConstants.OPEN) { this.socket = $websocketBackend.create(this.url, this.protocols); this.socket.onmessage = _angular2.default.bind(this, this._onMessageHandler); @@ -320,10 +321,6 @@ return self; } - if ($websocketBackend.isMocked && $websocketBackend.isMocked() && $websocketBackend.isConnected(this.url)) { - this._onMessageHandler($websocketBackend.mockSend()); - } - return promise; }; @@ -412,4 +409,4 @@ exports.default = _angular2.default.module('ngWebSocket'); module.exports = exports['default']; -}); +}); \ No newline at end of file diff --git a/dist/angular-websocket.min.js b/dist/angular-websocket.min.js index 0d82580..d8a7f43 100644 --- a/dist/angular-websocket.min.js +++ b/dist/angular-websocket.min.js @@ -1,2 +1,2 @@ -!function(e,t){if("function"==typeof define&&define.amd)define(["module","exports","angular","ws"],t);else if("undefined"!=typeof exports)t(module,exports,require("angular"),require("ws"));else{var o={exports:{}};t(o,o.exports,e.angular,e.ws),e.angularWebsocket=o.exports}}(this,function(e,t,o,n){"use strict";function s(e){return e&&e.__esModule?e:{"default":e}}function r(e,t,o,n){function s(t,o,n){n||!k(o)||C(o)||(n=o,o=void 0),this.protocols=o,this.url=t||"Missing URL",this.ssl=/(wss)/i.test(this.url),this.scope=n&&n.scope||e,this.rootScopeFailover=n&&n.rootScopeFailover&&!0,this.useApplyAsync=n&&n.useApplyAsync||!1,this.initialTimeout=n&&n.initialTimeout||500,this.maxTimeout=n&&n.maxTimeout||3e5,this.reconnectIfNotNormalClose=n&&n.reconnectIfNotNormalClose||!1,this.binaryType=n&&n.binaryType||"blob",this._reconnectAttempts=0,this.sendQueue=[],this.onOpenCallbacks=[],this.onMessageCallbacks=[],this.onErrorCallbacks=[],this.onCloseCallbacks=[],f(this._readyStateConstants),t?this._connect():this._setInternalState(0)}return s.prototype._readyStateConstants={CONNECTING:0,OPEN:1,CLOSING:2,CLOSED:3,RECONNECT_ABORTED:4},s.prototype._normalCloseCode=1e3,s.prototype._reconnectableStatusCodes=[4e3],s.prototype.safeDigest=function(e){e&&!this.scope.$$phase&&this.scope.$digest()},s.prototype.bindToScope=function(t){var o=this;return t&&(this.scope=t,this.rootScopeFailover&&this.scope.$on("$destroy",function(){o.scope=e})),o},s.prototype._connect=function(e){!e&&this.socket&&this.socket.readyState===this._readyStateConstants.OPEN||(this.socket=n.create(this.url,this.protocols),this.socket.onmessage=c["default"].bind(this,this._onMessageHandler),this.socket.onopen=c["default"].bind(this,this._onOpenHandler),this.socket.onerror=c["default"].bind(this,this._onErrorHandler),this.socket.onclose=c["default"].bind(this,this._onCloseHandler),this.socket.binaryType=this.binaryType)},s.prototype.fireQueue=function(){for(;this.sendQueue.length&&this.socket.readyState===this._readyStateConstants.OPEN;){var e=this.sendQueue.shift();this.socket.send(d(e.message)||"blob"!=this.binaryType?e.message:JSON.stringify(e.message)),e.deferred.resolve()}},s.prototype.notifyOpenCallbacks=function(e){for(var t=0;t-1)&&this.reconnect()},s.prototype._onErrorHandler=function(e){var t=this;t.useApplyAsync?t.scope.$applyAsync(function(){t.notifyErrorCallbacks(e)}):(t.notifyErrorCallbacks(e),t.safeDigest(!0))},s.prototype._onMessageHandler=function(e){function t(e,t,o){o=m.call(arguments,2),s.useApplyAsync?s.scope.$applyAsync(function(){e.apply(s,o)}):(e.apply(s,o),s.safeDigest(t))}for(var o,n,s=this,r=0;re||e>4)throw new Error("state must be an integer between 0 and 4, got: "+e);h||(this.readyState=e||this.socket.readyState),this._internalConnectionState=e,g(this.sendQueue,function(e){e.deferred.reject("Message cancelled due to closed socket connection")})},h&&h(s.prototype,"readyState",{get:function(){return this._internalConnectionState||this.socket.readyState},set:function(){throw new Error("The readyState property is read-only")}}),function(e,t,o){return new s(e,t,o)}}function i(e){this.create=function(e,t){var o=/wss?:\/\//.exec(e);if(!o)throw new Error("Invalid url provided");return t?new a(e,t):new a(e)},this.createWebSocketBackend=function(t,o){return e.warn("Deprecated: Please use .create(url, protocols)"),this.create(t,o)}}Object.defineProperty(t,"__esModule",{value:!0});var a,c=s(o),l="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol?"symbol":typeof e};if("object"===("undefined"==typeof t?"undefined":l(t))&&"function"==typeof require)try{a=n.Client||n.client||n}catch(u){}a=a||window.WebSocket||window.MozWebSocket;var p=c["default"].noop,f=Object.freeze?Object.freeze:p,h=Object.defineProperty,d=c["default"].isString,y=c["default"].isFunction,b=c["default"].isDefined,k=c["default"].isObject,C=c["default"].isArray,g=c["default"].forEach,m=Array.prototype.slice;Array.prototype.indexOf||(Array.prototype.indexOf=function(e){var t=this.length>>>0,o=Number(arguments[1])||0;for(o=0>o?Math.ceil(o):Math.floor(o),0>o&&(o+=t);t>o;o++)if(o in this&&this[o]===e)return o;return-1}),c["default"].module("ngWebSocket",[]).factory("$websocket",["$rootScope","$q","$timeout","$websocketBackend",r]).factory("WebSocket",["$rootScope","$q","$timeout","WebsocketBackend",r]).service("$websocketBackend",["$log",i]).service("WebSocketBackend",["$log",i]),c["default"].module("angular-websocket",["ngWebSocket"]),t["default"]=c["default"].module("ngWebSocket"),e.exports=t["default"]}); +!function(e,t){if("function"==typeof define&&define.amd)define(["module","exports","angular","ws"],t);else if("undefined"!=typeof exports)t(module,exports,require("angular"),require("ws"));else{var o={exports:{}};t(o,o.exports,e.angular,e.ws),e.angularWebsocket=o.exports}}(this,function(e,t,o,n){"use strict";function s(e){return e&&e.__esModule?e:{default:e}}function r(e,t,o,n){function s(t,o,n){n||!y(o)||b(o)||(n=o,o=void 0),this.protocols=o,this.url=t||"Missing URL",this.ssl=/(wss)/i.test(this.url),this.scope=n&&n.scope||e,this.rootScopeFailover=n&&n.rootScopeFailover&&!0,this.useApplyAsync=n&&n.useApplyAsync||!1,this.initialTimeout=n&&n.initialTimeout||500,this.maxTimeout=n&&n.maxTimeout||3e5,this.reconnectIfNotNormalClose=n&&n.reconnectIfNotNormalClose||!1,this.binaryType=n&&n.binaryType||"blob",this._reconnectAttempts=0,this.sendQueue=[],this.onOpenCallbacks=[],this.onMessageCallbacks=[],this.onErrorCallbacks=[],this.onCloseCallbacks=[],u(this._readyStateConstants),t?this._connect():this._setInternalState(0)}return s.prototype._readyStateConstants={CONNECTING:0,OPEN:1,CLOSING:2,CLOSED:3,RECONNECT_ABORTED:4},s.prototype._normalCloseCode=1e3,s.prototype._reconnectableStatusCodes=[4e3],s.prototype.safeDigest=function(e){e&&!this.scope.$$phase&&this.scope.$digest()},s.prototype.bindToScope=function(t){var o=this;return t&&(this.scope=t,this.rootScopeFailover&&this.scope.$on("$destroy",function(){o.scope=e})),o},s.prototype._connect=function(e){this.socket&&(this.socket.onmessage=null,this.socket.onopen=null,this.socket.onerror=null,this.socket.onclose=null,this.socket.close()),!e&&this.socket&&this.socket.readyState===this._readyStateConstants.OPEN||(this.socket=n.create(this.url,this.protocols),this.socket.onmessage=c.default.bind(this,this._onMessageHandler),this.socket.onopen=c.default.bind(this,this._onOpenHandler),this.socket.onerror=c.default.bind(this,this._onErrorHandler),this.socket.onclose=c.default.bind(this,this._onCloseHandler),this.socket.binaryType=this.binaryType)},s.prototype.fireQueue=function(){for(;this.sendQueue.length&&this.socket.readyState===this._readyStateConstants.OPEN;){var e=this.sendQueue.shift();this.socket.send(h(e.message)||"blob"!=this.binaryType?e.message:JSON.stringify(e.message)),e.deferred.resolve()}},s.prototype.notifyOpenCallbacks=function(e){for(var t=0;t-1)&&this.reconnect()},s.prototype._onErrorHandler=function(e){var t=this;t.useApplyAsync?t.scope.$applyAsync(function(){t.notifyErrorCallbacks(e)}):(t.notifyErrorCallbacks(e),t.safeDigest(!0))},s.prototype._onMessageHandler=function(e){function t(e,t,o){o=C.call(arguments,2),s.useApplyAsync?s.scope.$applyAsync(function(){e.apply(s,o)}):(e.apply(s,o),s.safeDigest(t))}for(var o,n,s=this,r=0;r4)throw new Error("state must be an integer between 0 and 4, got: "+e);p||(this.readyState=e||this.socket.readyState),this._internalConnectionState=e,k(this.sendQueue,function(e){e.deferred.reject("Message cancelled due to closed socket connection")})},p&&p(s.prototype,"readyState",{get:function(){return this._internalConnectionState||this.socket.readyState},set:function(){throw new Error("The readyState property is read-only")}}),function(e,t,o){return new s(e,t,o)}}function i(e){this.create=function(e,t){var o=/wss?:\/\//.exec(e);if(!o)throw new Error("Invalid url provided");return t?new a(e,t):new a(e)},this.createWebSocketBackend=function(t,o){return e.warn("Deprecated: Please use .create(url, protocols)"),this.create(t,o)}}Object.defineProperty(t,"__esModule",{value:!0});var a,c=s(o);if("undefined"==typeof window)try{a=n.Client||n.client||n}catch(e){}a=a||window.WebSocket||window.MozWebSocket;var l=c.default.noop,u=Object.freeze?Object.freeze:l,p=Object.defineProperty,h=c.default.isString,f=c.default.isFunction,d=c.default.isDefined,y=c.default.isObject,b=c.default.isArray,k=c.default.forEach,C=Array.prototype.slice;Array.prototype.indexOf||(Array.prototype.indexOf=function(e){var t=this.length>>>0,o=Number(arguments[1])||0;for(o=o<0?Math.ceil(o):Math.floor(o),o<0&&(o+=t);o -1; }; - $MockWebSocket.prototype.close = function () { - pendingCloses.push(true); + $MockWebSocket.prototype.close = function (code) { + pendingCloses.push({url: this.url, code: code ? code : 1000}); }; function createWebSocketBackend(url, protocols) { @@ -57,19 +76,61 @@ function $WebSocketBackend() { this.create = createWebSocketBackend; this.createWebSocketBackend = createWebSocketBackend; + function callOpenCallbacks(url) { + existingMocks[url].map(function(socketMock) { + if(socketMock.onopen && typeof socketMock.onopen === "function") { + socketMock.onopen(); + } + }); + } + + function callCloseCallbacks(url, code) { + existingMocks[url].map(function(socketMock) { + if(socketMock.onclose && typeof socketMock.onclose === "function") { + socketMock.onclose({code: code}); + } + }); + } + + function callMessageCallbacks(url, data) { + if(existingMocks[url]) { + existingMocks[url].map(function(socketMock) { + if(socketMock.onmessage && typeof socketMock.onmessage === "function") { + socketMock.onmessage({data: JSON.stringify(data)}); + } + }); + } + } + + function setReadyState(url, state) { + if(existingMocks[url]) { + existingMocks[url].map(function(socketMock) { + socketMock.readyState = state; + }); + } + } + this.flush = function () { var url, msg, config; while (url = pendingConnects.shift()) { var i = connectQueue.indexOf(url); if (i > -1) { connectQueue.splice(i, 1); + callOpenCallbacks(url); + setReadyState(url, 1); } // if (config && config.url) { // } } - while (pendingCloses.shift()) { - closeQueue.shift(); + var pendingClose; + while (pendingClose = pendingCloses.shift()) { + var i = closeQueue.indexOf(pendingClose.url); + if(i > -1) { + closeQueue.splice(i, 1); + callCloseCallbacks(pendingClose.url, pendingClose.code); + setReadyState(pendingClose.url, 3); + } } while (msg = pendingSends.shift()) { @@ -84,6 +145,10 @@ function $WebSocketBackend() { sendQueue.splice(j, 1); } } + + while (msg = pendingMessages.shift()) { + callMessageCallbacks(msg.url, msg.data); + } }; this.expectConnect = function (url, protocols) { @@ -91,8 +156,8 @@ function $WebSocketBackend() { // connectQueue.push({url: url, protocols: protocols}); }; - this.expectClose = function () { - closeQueue.push(true); + this.expectClose = function (url) { + closeQueue.push(url); }; this.expectSend = function (msg) { diff --git a/src/angular-websocket.js b/src/angular-websocket.js index 3f4e919..3456a10 100644 --- a/src/angular-websocket.js +++ b/src/angular-websocket.js @@ -85,7 +85,6 @@ function $WebSocketProvider($rootScope, $q, $timeout, $websocketBackend) { } - $WebSocket.prototype._readyStateConstants = { 'CONNECTING': 0, 'OPEN': 1, @@ -120,6 +119,13 @@ function $WebSocketProvider($rootScope, $q, $timeout, $websocketBackend) { }; $WebSocket.prototype._connect = function _connect(force) { + if(this.socket) { + this.socket.onmessage = null; + this.socket.onopen = null; + this.socket.onerror = null; + this.socket.onclose = null; + this.socket.close(); + } if (force || !this.socket || this.socket.readyState !== this._readyStateConstants.OPEN) { this.socket = $websocketBackend.create(this.url, this.protocols); this.socket.onmessage = angular.bind(this, this._onMessageHandler); @@ -299,11 +305,6 @@ function $WebSocketProvider($rootScope, $q, $timeout, $websocketBackend) { return self; } - if ($websocketBackend.isMocked && $websocketBackend.isMocked() && - $websocketBackend.isConnected(this.url)) { - this._onMessageHandler($websocketBackend.mockSend()); - } - return promise; }; diff --git a/test/angular-websocket.spec.js b/test/angular-websocket.spec.js index a5e4f4e..d6c8527 100644 --- a/test/angular-websocket.spec.js +++ b/test/angular-websocket.spec.js @@ -154,6 +154,11 @@ describe('angular-websocket', function() { expect(typeof ws.socket.onerror).toBe('function'); expect(typeof ws.socket.onclose).toBe('function'); }); + + it('should set readyState', function() { + $websocketBackend.flush(); + expect(ws.readyState).toEqual(ws._readyStateConstants.OPEN); + }); }); @@ -174,7 +179,7 @@ describe('angular-websocket', function() { }); it('should call close on the underlying socket', function() { - $websocketBackend.expectClose(); + $websocketBackend.expectClose(url); ws.close(); }); @@ -186,10 +191,17 @@ describe('angular-websocket', function() { it('should accept a force param to close the socket even if bufferedAmount is greater than 0', function() { - $websocketBackend.expectClose(); + $websocketBackend.expectClose(url); ws.socket.bufferedAmount = 5; ws.close(true); }); + + it('should set readyState', function() { + $websocketBackend.expectClose(url); + ws.close(); + $websocketBackend.flush(); + expect(ws.readyState).toEqual(ws._readyStateConstants.CLOSED); + }); }); @@ -199,7 +211,7 @@ describe('angular-websocket', function() { $websocketBackend.expectConnect(url); var ws = $websocket(url); - $websocketBackend.expectClose(); + $websocketBackend.expectClose(url); ws.reconnect(); $websocketBackend.flush(); @@ -918,6 +930,46 @@ describe('angular-websocket', function() { }); // end ._onErrorHandler() + describe('eventHandlers', function() { + var url, ws; + + beforeEach(function() { + url = 'ws://foo'; + $websocketBackend.expectConnect(url); + ws = $websocket(url); + }); + + it('should be automatically called on open', function() { + var spy = jasmine.createSpy('callback'); + ws.onOpenCallbacks.push(spy); + $websocketBackend.flush(); + expect(spy).toHaveBeenCalled(); + }); + + it('should be automatically called on close', function() { + var spy = jasmine.createSpy('callback'); + ws.onCloseCallbacks.push(spy); + $websocketBackend.expectClose(url); + ws.close(); + $websocketBackend.flush(); + expect(spy).toHaveBeenCalled(); + }); + + it("should be automatically called on fake close", function() { + var spy = jasmine.createSpy('callback'); + ws.onCloseCallbacks.push(spy); + $websocketBackend.fakeClose(url); + $websocketBackend.flush(); + expect(spy).toHaveBeenCalled(); + }); + it("should be automatically called on fake send", function() { + var spy = jasmine.createSpy('callback'); + ws.onMessage(spy); + $websocketBackend.fakeMessage(url, {data: "test"}); + $websocketBackend.flush(); + expect(spy).toHaveBeenCalled(); + }); + }); }); // end $websocketBackend }); // end $websocket