2
schangxiang@126.com
2024-08-16 b47c50a2a514def7374b32d7194b2c599cba5625
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
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
describe('Module: oc.lazyLoad', function() {
    'use strict';
 
    var $ocLazyLoad,
        $rootScope,
        $controller,
        $injector,
        $filter,
        $compile,
        $httpBackend,
        $log,
        element,
        lazyLoadUrl = '/base/tests/unit/lazyLoad/',
        triggerDigests = function() {
            return setInterval(function() {
                $rootScope.$digest();
            }, 10)
        };
 
    describe('with app1', function() {
 
        beforeEach(function() {
            module('app1');
 
            // get the $httpBackend from E2E tests (because the one for unit tests sucks)
            module('ngMockE2E');
            module(function($provide) {
                //retrieve the $httpBackend from module ng and override $delegate from ngMockE2E
                angular.injector(['ng'])
                    .invoke(function($httpBackend) {
                        $provide.value('$delegate', $httpBackend);
                    });
 
                //retrieve the $httpBackend from module ng and override $delegate from ngMockE2E
                angular.injector(['ngMockE2E'])
                    .invoke(['$httpBackend', function(_$httpBackend_) {
                        $httpBackend = _$httpBackend_;
                    }]);
 
                $provide.value('$httpBackend', $httpBackend);
            });
 
            // get the services for all tests
            inject(function(_$ocLazyLoad_, _$rootScope_, _$controller_, _$injector_, _$filter_, _$compile_, _$log_) {
                $ocLazyLoad = _$ocLazyLoad_;
                $rootScope = _$rootScope_;
                $controller = _$controller_;
                $injector = _$injector_;
                $filter = _$filter_;
                $compile = _$compile_;
                $log = _$log_;
            });
 
            // allow requests for lazy loaded files
            $httpBackend.when('GET', new RegExp(lazyLoadUrl)).passThrough();
        });
 
        it('service should be defined', function() {
            expect($ocLazyLoad).toBeDefined();
        });
 
        it('getModules should be working', function() {
            expect($ocLazyLoad.getModules).toBeDefined();
            expect(angular.isArray($ocLazyLoad.getModules())).toBe(true);
        });
 
        it('loadedModules should be working', function() {
            expect($ocLazyLoad.getModules()).toEqual(['ng', 'oc.lazyLoad']);
        });
 
        it('angular.bootstrap should add the module to the loaded list', function() {
            angular.bootstrap(document, ['app1']);
            expect($ocLazyLoad.getModules()).toEqual(['ng', 'oc.lazyLoad', 'app1']);
        });
 
        it('isLoaded should be working', function() {
            expect($ocLazyLoad.isLoaded).toBeDefined();
            expect($ocLazyLoad.isLoaded).toThrowError('You need to define the module(s) name(s)');
            expect($ocLazyLoad.isLoaded('app1')).toBe(true); // string arg
            expect($ocLazyLoad.isLoaded(['ng', 'app1'])).toBe(true); // array arg
            expect($ocLazyLoad.isLoaded('noModule')).toBe(false);
            expect($ocLazyLoad.isLoaded(['ng', 'noModule'])).toBe(false);
        });
 
        it('getModuleConfig should be working', function() {
            expect($ocLazyLoad.getModuleConfig).toBeDefined();
            expect($ocLazyLoad.getModuleConfig).toThrowError('You need to give the name of the module to get');
            expect($ocLazyLoad.getModuleConfig('noModule')).toBe(null);
            expect($ocLazyLoad.getModuleConfig('test')).toEqual({name: 'test', files: []});
        });
 
        it('setModuleConfig should be working', function() {
            expect($ocLazyLoad.setModuleConfig).toBeDefined();
            expect($ocLazyLoad.setModuleConfig).toThrowError('You need to give the module config object to set');
            expect($ocLazyLoad.setModuleConfig({name: 'test2'})).toEqual({name: 'test2'});
            expect($ocLazyLoad.getModuleConfig('test2')).toEqual({name: 'test2'}); // check if set worked
        });
 
        it('should be able to lazy load a module', function(done) {
            var interval = triggerDigests(),
                templateUrl = lazyLoadUrl + 'test.html',
                testModule = [
                    lazyLoadUrl + 'testModule.js',
                    lazyLoadUrl + 'test.css',
                    templateUrl
                ];
 
            // create spies for the following tests
            window.spy = jasmine.createSpyObj('spy', ['config', 'run', 'ctrl', 'service', 'filter', 'directive', 'decorator']);
 
            $ocLazyLoad.load(testModule).then(function success(res) {
                window.clearInterval(interval);
 
                // Test the module loading
                expect(function() {
                    angular.module('testModule')
                }).not.toThrow();
                expect(angular.module('testModule')).toBeDefined();
 
                // execute controller
                expect(function() {
                    $controller('TestCtrl', {$scope: $rootScope.$new()});
                }).not.toThrow();
 
                // instantiate service
                expect(function() {
                    $injector.get('testService');
                }).not.toThrow();
 
                // execute filter
                expect(function() {
                    $filter('testFilter');
                }).not.toThrow();
 
                // Compile a piece of HTML containing the directive
                element = $compile("<test></test>")($rootScope.$new());
 
                // Test the template loading
                var $templateCache;
                expect(function() {
                    $templateCache = $injector.get('$templateCache');
                }).not.toThrow();
                expect($templateCache.get('/partials/test.html')).toEqual('Test partial content');
 
                // Test the css loading
                var links = document.getElementsByTagName('link');
                expect(links.length).toBeGreaterThan(0);
                expect(function() {
                    links[links.length - 1].sheet.cssRules;
                }).not.toThrow(); // this only works if a stylesheet has been loaded
                expect(links[links.length - 1].sheet.cssRules).toBeDefined();
 
                // because debug is set to false, we shouldn't have any log
                $log.assertEmpty();
 
                done();
            }, function error(err) {
                window.clearInterval(interval);
                throw err;
            });
        });
 
        it('should be able to execute config blocks', function() {
            expect(window.spy.config).toHaveBeenCalledWith('config1');
            expect(window.spy.config).toHaveBeenCalledWith('config2');
            expect(window.spy.config.calls.count()).toEqual(2);
        });
 
        it('should be able to execute run blocks', function() {
            expect(window.spy.run).toHaveBeenCalledWith('run1');
            expect(window.spy.run).toHaveBeenCalledWith('run2');
            expect(window.spy.run.calls.count()).toEqual(2);
        });
 
        it('should be able to define controllers', function() {
            expect(window.spy.ctrl).toHaveBeenCalledWith('ctrl');
            expect(window.spy.ctrl.calls.count()).toEqual(1);
        });
 
        it('should be able to define services', function() {
            expect(window.spy.service).toHaveBeenCalledWith('service');
            expect(window.spy.service.calls.count()).toEqual(1);
        });
 
        it('should be able to define filters', function() {
            expect(window.spy.filter).toHaveBeenCalledWith('filter');
            expect(window.spy.filter.calls.count()).toEqual(1);
        });
 
        it('should be able to define directives', function() {
            expect(window.spy.directive).toHaveBeenCalledWith('directive');
            expect(window.spy.directive.calls.count()).toEqual(1);
            expect(element.html()).toContain("Test template");
        });
 
        if(angular.version.minor > 3) { // only in angular 1.4+
            it('should be able to define decorators', function() {
                expect(window.spy.decorator).toHaveBeenCalledWith('decorator');
                expect(window.spy.service.calls.count()).toEqual(1);
            });
        }
 
        it('should be able to resolve a file name with url parameters', function(done) {
            var interval = triggerDigests(),
                testModule = [
                    lazyLoadUrl + 'test.html?v=xy12'
                ];
 
            $ocLazyLoad.load(testModule).then(function success(res) {
                window.clearInterval(interval);
 
                var $templateCache = $injector.get('$templateCache');
                expect($templateCache.get('/partials/test.html')).toEqual('Test partial content');
 
                // because debug is set to false, we shouldn't have any log
                $log.assertEmpty();
 
                done();
            }, function error(err) {
                window.clearInterval(interval);
                throw err;
            });
        });
 
        it('should be able to lazy load a module when specifying a file type', function(done) {
            var interval = triggerDigests(),
                testModuleNoExt = [
                    {type: 'js', path: lazyLoadUrl + 'testModule.fakejs'},
                    lazyLoadUrl + 'test.css',
                    'html!' + lazyLoadUrl + 'test.html'
                ];
 
            $ocLazyLoad.load(testModuleNoExt).then(function success(res) {
                window.clearInterval(interval);
 
                // Test the module loading
                expect(angular.module('testModuleNoExt')).toBeDefined();
 
                // execute controller
                $controller('TestCtrlNoExt', {$scope: $rootScope.$new()});
 
                // instantiate service
                $injector.get('testServiceNoExt');
 
                // execute filter
                $filter('testFilterNoExt');
 
                // Compile a piece of HTML containing the directive
                element = $compile("<test-no-ext></test-no-ext>")($rootScope.$new());
 
                // Test the template loading
                var $templateCache = $injector.get('$templateCache');
                expect($templateCache.get('/partials/test.html')).toEqual('Test partial content');
 
                // Test the css loading
                var links = document.getElementsByTagName('link');
                expect(links.length).toBeGreaterThan(0);
                expect(function() {
                    links[links.length - 1].sheet.cssRules;
                }).not.toThrow(); // this only works if a stylesheet has been loaded
                expect(links[links.length - 1].sheet.cssRules).toBeDefined();
 
                // because debug is set to false, we shouldn't have any log
                $log.assertEmpty();
 
                done();
            }, function error(err) {
                window.clearInterval(interval);
                throw err;
            });
        });
 
        it('should be able to lazy load a module when the url ends with a hash', function(done) {
            var interval = triggerDigests();
 
            $ocLazyLoad.load(lazyLoadUrl + 'testModule4.js#hash').then(function success(res) {
                window.clearInterval(interval);
 
                // Test the module loading
                expect(angular.module('testModule4')).toBeDefined();
 
                // Test the module loading
                expect(res).toBeDefined();
 
                // because debug is set to false, we shouldn't have any log
                $log.assertEmpty();
 
                done();
            }, function error(err) {
                window.clearInterval(interval);
                throw err;
            });
        });
 
        it('should reject the promise when the jsLoader is unable to load a file', function(done) {
            var interval = triggerDigests();
 
            $ocLazyLoad.load(lazyLoadUrl + 'noFile.js').then(function success(res) {
                window.clearInterval(interval);
                throw(new Error('failed!'));
            }, function error(err) {
                expect(err.message).toEqual('Unable to load ' + lazyLoadUrl + 'noFile.js');
                window.clearInterval(interval);
                done();
            });
        });
 
        // test 17
        it('should reject the promise when the cssLoader is unable to load a file', function(done) {
            var interval = triggerDigests();
 
            $ocLazyLoad.load(lazyLoadUrl + 'noFile.css').then(function success(res) {
                window.clearInterval(interval);
                throw(new Error('failed!'));
            }, function error(err) {
                expect(err.message).toEqual('Unable to load ' + lazyLoadUrl + 'noFile.css');
                window.clearInterval(interval);
                done();
            });
        });
 
        it('should reject the promise when the templateLoader is unable to load a file', function(done) {
            var interval = triggerDigests();
 
            $ocLazyLoad.load(lazyLoadUrl + 'noFile.html').then(function success(res) {
                window.clearInterval(interval);
                throw(new Error('failed!'));
            }, function error(err) {
                expect(err.message).toEqual('Unable to load template file "' + lazyLoadUrl + 'noFile.html": NOT FOUND');
                window.clearInterval(interval);
                done();
            });
        });
 
        it('should throw if you try to load a module with missing dependencies', function(done) {
            var interval = triggerDigests();
 
            $ocLazyLoad.load([lazyLoadUrl + 'testModule3.js']).then(function success(res) {
                window.clearInterval(interval);
                throw(new Error('failed!'));
            }, function error(err) {
                expect(err).toBeDefined();
                window.clearInterval(interval);
                done();
            });
        });
 
        it('should be able to load a module with dependencies', function(done) {
            var interval = triggerDigests();
 
            $ocLazyLoad.load([lazyLoadUrl + 'testModule2.js', lazyLoadUrl + 'testModule3.js']).then(function success(res) {
                expect(function() {
                    angular.module('testModule2');
                    angular.module('testModule3');
                }).not.toThrow();
                window.clearInterval(interval);
                done();
            }, function error(err) {
                window.clearInterval(interval);
                throw err;
            });
        });
 
        it('should be able to load a module with params', function(done) {
            var interval = triggerDigests();
 
            $ocLazyLoad.load({files: [lazyLoadUrl + 'testModule2.js'], cache: false}).then(function success(res) {
                expect(function() {
                    angular.module('testModule2');
                }).not.toThrow();
                window.clearInterval(interval);
                done();
            }, function error(err) {
                window.clearInterval(interval);
                throw err;
            });
        });
 
        it('should be able to load a component defined as an object', function(done) {
            var interval = triggerDigests();
 
            $ocLazyLoad.load(lazyLoadUrl + 'testModule5.js').then(function success(res) {
                expect(function() {
                    angular.module('testModule5');
                }).not.toThrow();
 
                // execute controller
                expect(function() {
                    $controller('testModule5Ctrl', {$scope: $rootScope.$new()});
                }).not.toThrow();
 
                window.clearInterval(interval);
                done();
            }, function error(err) {
                window.clearInterval(interval);
                throw err;
            });
        });
 
        it('should be able to load a module with insertBefore', function(done) {
            var interval = triggerDigests();
 
            $ocLazyLoad.load({files: [lazyLoadUrl + 'testModule6.js'], insertBefore: "title"}).then(function success(res) {
                expect(function() {
                    angular.module('testModule6');
                }).not.toThrow();
                window.clearInterval(interval);
                done();
            }, function error(err) {
                window.clearInterval(interval);
                throw err;
            });
        });
 
        it('should be able to load files with the param serie set to true', function(done) {
            var interval = triggerDigests(),
                params = {files: [lazyLoadUrl + 'testModule5.js', lazyLoadUrl + 'testModule6.js'], serie: true};
 
            $ocLazyLoad.load(params).then(function success(res) {
                expect(function() {
                    angular.module('testModule5');
                    angular.module('testModule6');
                }).not.toThrow();
 
               expect(params.files.length).toEqual(2); // it should not change the original params
 
                window.clearInterval(interval);
                done();
            }, function error(err) {
                window.clearInterval(interval);
                throw err;
            });
        });
 
        it('should attach and then compile an element', function(done) {
            var fileToLoad = lazyLoadUrl + 'myContainer.js';
            var scope = $rootScope.$new();
            var interval;
 
            $ocLazyLoad.load(fileToLoad).then(function success(res) {
              scope.fileToLoad = fileToLoad;
                var element = $compile('<div oc-lazy-load="fileToLoad"><my-container></my-container></div>')(scope);
                setTimeout(function() {
                    // Should be able to save an element during compilation and reference
                    // it after the element has been attached to the parent DOM.
                    // IE throws "Invalid calling object" if the element is compiled and then attached.
                    expect(scope.vm.highlanders.length).toBe(1);
 
                    window.clearInterval(interval);
                    done();
                }, interval * 2);
            });
 
            interval = triggerDigests();
        });
    });
});