aboutsummaryrefslogtreecommitdiffstats
path: root/test/InjectorSpec.js
blob: 6c0e96688a4ee0ee7804d0f5a64ab9118d7cbb00 (plain)
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
'use strict';

describe('injector', function() {
  var providers;
  var injector;

  beforeEach(inject(function($injector, $provide) {
    providers = function(name, factory, decoration){
      $provide.factory(name, extend(factory, decoration||{}));
    };
    injector = $injector;
  }));

  it("should return same instance from calling provider", function() {
    var instance = {},
        original = instance;
    providers('instance', function() { return instance; });
    expect(injector('instance')).toEqual(instance);
    instance = 'deleted';
    expect(injector('instance')).toEqual(original);
  });


  it('should inject providers', function() {
    providers('a', function() {return 'Mi';});
    providers('b', function(mi) {return mi+'sko';}, {$inject:['a']});
    expect(injector('b')).toEqual('Misko');
  });


  it('should resolve dependency graph and instantiate all services just once', function() {
    var log = [];

//          s1
//        /  | \
//       /  s2  \
//      /  / | \ \
//     /s3 < s4 > s5
//    //
//   s6


    providers('s1', function() { log.push('s1'); }, {$inject: ['s2', 's5', 's6']});
    providers('s2', function() { log.push('s2'); }, {$inject: ['s3', 's4', 's5']});
    providers('s3', function() { log.push('s3'); }, {$inject: ['s6']});
    providers('s4', function() { log.push('s4'); }, {$inject: ['s3', 's5']});
    providers('s5', function() { log.push('s5'); });
    providers('s6', function() { log.push('s6'); });

    injector('s1');

    expect(log).toEqual(['s6', 's5', 's3', 's4', 's2', 's1']);
  });


  it('should provide useful message if no provider', function() {
    expect(function() {
      injector('idontexist');
    }).toThrow("Unknown provider for 'idontexist'.");
  });

  it('should proved path to the missing provider', function() {
    providers('a', function(idontexist) {return 1;});
    providers('b', function(a) {return 2;});
    expect(function() {
      injector('b');
    }).toThrow("Unknown provider for 'idontexist' <- 'a' <- 'b'.");
  });


  describe('invoke', function() {
    var args;

    beforeEach(function() {
      args = null;
      providers('a', function() {return 1;});
      providers('b', function() {return 2;});
    });


    function fn(a, b, c, d) {
      args = [this, a, b, c, d];
      return a + b + c + d;
    }


    it('should call function', function() {
      fn.$inject = ['a', 'b', 'c', 'd'];
      injector.invoke({name:"this"}, fn,  {c:3, d:4});
      expect(args).toEqual([{name:'this'}, 1, 2, 3, 4]);
    });


    it('should treat array as annotations', function() {
      injector.invoke({name:"this"}, ['a', 'b', 'c', 'd', fn], {c:3, d:4});
      expect(args).toEqual([{name:'this'}, 1, 2, 3, 4]);
    });


    it('should invoke the passed in function with all of the dependencies as arguments', function(){
      providers('c', function() {return 3;});
      providers('d', function() {return 4;});
      expect(injector(['a', 'b', 'c', 'd', fn])).toEqual(10);
    });


    it('should fail with errors if not function or array', function() {
      expect(function() {
        injector.invoke({}, {});
      }).toThrow("Argument 'fn' is not a function, got Object");
      expect(function() {
        injector.invoke({}, ['a', 123]);
      }).toThrow("Argument 'fn' is not a function, got number");
    });
  });

  describe('annotation', function() {
    it('should return $inject', function() {
      function fn() {}
      fn.$inject = ['a'];
      expect(inferInjectionArgs(fn)).toBe(fn.$inject);
      expect(inferInjectionArgs(function() {})).toEqual([]);
      expect(inferInjectionArgs(function () {})).toEqual([]);
      expect(inferInjectionArgs(function  () {})).toEqual([]);
      expect(inferInjectionArgs(function /* */ () {})).toEqual([]);
    });

    it('should create $inject', function() {
      // keep the multi-line to make sure we can handle it
      function $f_n0 /*
          */(
          $a, // x, <-- looks like an arg but it is a comment
          b_, /* z, <-- looks like an arg but it is a
                 multi-line comment
                 function (a, b) {}
                 */
          _c,
          /* {some type} */ d) { extraParans();}
      expect(inferInjectionArgs($f_n0)).toEqual(['$a', 'b_', '_c',  'd']);
      expect($f_n0.$inject).toEqual(['$a', 'b_', '_c',  'd']);
    });

    it('should handle no arg functions', function() {
      function $f_n0() {}
      expect(inferInjectionArgs($f_n0)).toEqual([]);
      expect($f_n0.$inject).toEqual([]);
    });

    it('should handle args with both $ and _', function() {
      function $f_n0($a_) {}
      expect(inferInjectionArgs($f_n0)).toEqual(['$a_']);
      expect($f_n0.$inject).toEqual(['$a_']);
    });

    it('should throw on non function arg', function() {
      expect(function() {
        inferInjectionArgs({});
      }).toThrow();
    });

  });


  it('should have $injector', function() {
    var $injector = createInjector();
    expect($injector('$injector')).toBe($injector);
  });

  it('should define module', function() {
    var log = '';
    var injector = createInjector([function($provide) {
      $provide.value('value', 'value;');
      $provide.factory('fn', valueFn('function;'));
      $provide.service('service', function() {
        this.$get = valueFn('service;');
      });
    }, function(valueProvider, fnProvider, serviceProvider) {
      log += valueProvider.$get() + fnProvider.$get() + serviceProvider.$get();
    }])(function(value, fn, service) {
      log += '->' + value + fn + service;
    });
    expect(log).toEqual('value;function;service;->value;function;service;');
  });


  describe('module', function() {
    it('should provide $injector and $provide even when no module is requested', function() {
      var $provide,
          $injector = createInjector([
            angular.extend(function(p) { $provide = p; }, {$inject: ['$provide']})
          ]);
      expect($injector('$injector')).toBe($injector);
      expect($injector('$provide')).toBe($provide);
    });


    it('should load multiple function modules and infer inject them', function() {
      var a = 'junk';
      var $injector = createInjector([
        function() {
          a = 'A'; // reset to prove we ran
        },
        function($provide) {
          $provide.value('a', a);
        },
        angular.extend(function(p, serviceA) {
          p.value('b', serviceA.$get() + 'B' );
        }, {$inject:['$provide', 'aProvider']}),
        ['$provide', 'bProvider', function(p, serviceB) {
          p.value('c', serviceB.$get() + 'C');
        }]
      ]);
      expect($injector('a')).toEqual('A');
      expect($injector('b')).toEqual('AB');
      expect($injector('c')).toEqual('ABC');
    });


    it('should run symbolic modules', function() {
      var $injector = createInjector(['myModule'], {
        myModule: ['$provide', function(provide) {
          provide.value('a', 'abc');
        }]
      });
      expect($injector('a')).toEqual('abc');
    });

    it('should error on invalid madule name', function(){
      expect(function(){
        createInjector(['IDontExist'], {});
      }).toThrow("Module 'IDontExist' is not defined!");
    });


    describe('$provide', function() {
      describe('value', function(){
        it('should configure $provide values', function() {
          expect(createInjector([function($provide) {
            $provide.value('value', 'abc');
          }])('value')).toEqual('abc');
        });
      });


      describe('factory', function(){
        it('should configure $provide factory function', function() {
          expect(createInjector([function($provide) {
            $provide.factory('value', valueFn('abc'));
          }])('value')).toEqual('abc');
        });
      });


      describe('service', function(){
        it('should configure $provide service object', function() {
          expect(createInjector([function($provide) {
            $provide.service('value', {
              $get: valueFn('abc')
            });
          }])('value')).toEqual('abc');
        });


        it('should configure $provide service type', function() {
          function Type() {};
          Type.prototype.$get = function() {
            expect(this instanceof Type).toBe(true);
            return 'abc';
          };
          expect(createInjector([function($provide) {
            $provide.service('value', Type);
          }])('value')).toEqual('abc');
        });
      });
    });


    describe('error handling', function() {
      it('should handle wrong argument type', function() {
        expect(function() {
          createInjector([
            {}
          ], {});
        }).toThrow("Argument 'module' is not a function, got Object");
      });


      it('should handle exceptions', function() {
        expect(function() {
          createInjector([function() {
            throw 'MyError';
          }], {});
        }).toThrow('MyError');
      });


      it('should handle no module alias', function() {
        expect(function() {
          createInjector([function(dontExist) {
          }], {});
        }).toThrow("Unknown provider for 'dontExist'.");
      });
    });
  });


  describe('retrieval', function() {
    var instance,
        $injector,
        $provide;
    
    beforeEach(function() {
      $injector = createInjector([ ['$provide', function(provide) {
        ($provide = provide).value('instance', instance = {name:'angular'});
      }]]);
    });


    it('should retrieve by name and cache instance', function() {
      expect(instance).toEqual({name: 'angular'});
      expect($injector('instance')).toBe(instance);
      expect($injector('instance')).toBe(instance);
    });
    
    
    it('should call functions and infer arguments', function() {
      expect($injector(function(instance) { return instance; })).toBe(instance);
      expect($injector(function(instance) { return instance; })).toBe(instance);
    });
  });


  describe('method invoking', function() {
    var $injector;

    beforeEach(function() {
      $injector = createInjector([ function($provide) {
        $provide.value('book', 'moby');
        $provide.value('author', 'melville');
      }]);
    });


    it('should invoke method', function() {
      expect($injector(function(book, author) { return author + ':' + book;})).toEqual('melville:moby');
      expect($injector.invoke($injector, function(book, author) {
        expect(this).toEqual($injector);
        return author + ':' + book;})).toEqual('melville:moby');
    });


    it('should invoke method with locals', function() {
      expect($injector(function(book, author) { return author + ':' + book;})).toEqual('melville:moby');
      expect($injector.invoke($injector,
        function(book, author, chapter) {
          expect(this).toEqual($injector);
          return author + ':' + book + '-' + chapter;
        }, {author:'m', chapter:'ch1'})).toEqual('m:moby-ch1');
    });


    it('should invoke method which is annotated', function() {
      expect($injector(extend(function(b, a) { return a + ':' + b}, {$inject:['book', 'author']}))).
        toEqual('melville:moby');
      expect($injector.invoke($injector, extend(function(b, a) {
        expect(this).toEqual($injector);
        return a + ':' + b;
      }, {$inject:['book', 'author']}))).toEqual('melville:moby');
    });


    it('should invoke method which is an array of annotation', function() {
      expect($injector(function(book, author) { return author + ':' + book;})).toEqual('melville:moby');
      expect($injector.invoke($injector, function(book, author) {
        expect(this).toEqual($injector);
        return author + ':' + book;
      })).toEqual('melville:moby');
    });

    
    it('should throw usefull error on wrong argument type]', function() {
      expect(function(){
        $injector.invoke(null, {});
      }).toThrow("Argument 'fn' is not a function, got Object");
    });
  });

  describe('service instantiation', function() {
    var $injector;

    beforeEach(function() {
      $injector = createInjector([ function($provide) {
        $provide.value('book', 'moby');
        $provide.value('author', 'melville');
      }]);
    });


    function Type(book, author) {
      this.book = book;
      this.author = author;
    }
    Type.prototype.title = function() {
      return this.author + ': ' + this.book;
    };


    it('should instantiate object and preserve constructor property and be instanceof', function() {
      var t = $injector.instantiate(Type);
      expect(t.book).toEqual('moby');
      expect(t.author).toEqual('melville');
      expect(t.title()).toEqual('melville: moby');
      expect(t instanceof Type).toBe(true);
    });


    it('should allow constructor to return different object', function() {
      var t = $injector.instantiate(function() { return 'ABC'; });
      expect(t).toBe('ABC');
    });


    it('should handle constructor exception', function() {
      expect(function() {
        $injector.instantiate(function() { throw 'MyError'; });
      }).toThrow('MyError');
    });
  });
});