-
Notifications
You must be signed in to change notification settings - Fork 10
/
angular-socket.io-mock.js
executable file
·78 lines (69 loc) · 2.5 KB
/
angular-socket.io-mock.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/* global angular: false */
var ng = angular.module('btford.socket-io',[])
ng.provider('socketFactory',function(){
var defaultPrefix = 'socket:';
this.$get = function($rootScope){
return function socketFactory (options) {
options = options || {};
var prefix = options.prefix === undefined ? defaultPrefix : options.prefix;
var defaultScope = options.scope || $rootScope;
var obj = {};
obj.events = {};
obj.emits = {};
// intercept 'on' calls and capture the callbacks
obj.on = function(eventName, callback){
if(!this.events[eventName]) this.events[eventName] = [];
this.events[eventName].push(callback);
};
// intercept 'once' calls and treat them as 'on'
obj.once = obj.on;
// intercept 'emit' calls from the client and record them to assert against in the test
obj.emit = function(eventName){
var args = Array.prototype.slice.call(arguments,1);
if(!this.emits[eventName])
this.emits[eventName] = [];
this.emits[eventName].push(args);
};
// when socket.on('someEvent', fn (data) { ... }),
// call scope.$broadcast('someEvent', data)
obj.forward = function (events, scope) {
var self = this;
if (events instanceof Array === false) {
events = [events];
}
if (!scope) {
scope = $rootScope;
}
events.forEach(function (eventName) {
var prefixedEvent = prefix + eventName;
obj.on(eventName, function (data) {
scope.$broadcast(prefixedEvent, data);
});
});
};
//simulate an inbound message to the socket from the server (only called from the test)
obj.receive = function(eventName){
var args = Array.prototype.slice.call(arguments,1);
if (this.events[eventName]) {
angular.forEach(this.events[eventName], function(callback){
$rootScope.$apply(function() {
callback.apply(this, args)
});
});
};
if (this.emits[eventName]) {
angular.forEach(this.emits[eventName], function(emit){
var lastIndex = emit.length -1;
if('function' === typeof emit[lastIndex] && !emit[lastIndex].acknowledged){
$rootScope.$apply(function() {
emit[lastIndex].acknowledged = true;
emit[lastIndex].apply(this, args);
});
};
});
};
};
return obj;
};
};
});