Best JavaScript code snippet using ng-mocks
injectorSpec.js
Source:injectorSpec.js
1'use strict';2describe('injector', function() {3 var providers;4 var injector;5 var providerInjector;6 beforeEach(module(function($provide, $injector) {7 providers = function(name, factory, annotations) {8 $provide.factory(name, extend(factory, annotations||{}));9 };10 providerInjector = $injector;11 }));12 beforeEach(inject(function($injector){13 injector = $injector;14 }));15 it("should return same instance from calling provider", function() {16 var instance = {},17 original = instance;18 providers('instance', function() { return instance; });19 expect(injector.get('instance')).toEqual(instance);20 instance = 'deleted';21 expect(injector.get('instance')).toEqual(original);22 });23 it('should inject providers', function() {24 providers('a', function() {return 'Mi';});25 providers('b', function(mi) {return mi+'sko';}, {$inject:['a']});26 expect(injector.get('b')).toEqual('Misko');27 });28 it('should resolve dependency graph and instantiate all services just once', function() {29 var log = [];30// s131// / | \32// / s2 \33// / / | \ \34// /s3 < s4 > s535// //36// s637 providers('s1', function() { log.push('s1'); }, {$inject: ['s2', 's5', 's6']});38 providers('s2', function() { log.push('s2'); }, {$inject: ['s3', 's4', 's5']});39 providers('s3', function() { log.push('s3'); }, {$inject: ['s6']});40 providers('s4', function() { log.push('s4'); }, {$inject: ['s3', 's5']});41 providers('s5', function() { log.push('s5'); });42 providers('s6', function() { log.push('s6'); });43 injector.get('s1');44 expect(log).toEqual(['s6', 's3', 's5', 's4', 's2', 's1']);45 });46 it('should allow query names', function() {47 providers('abc', function () { return ''; });48 expect(injector.has('abc')).toBe(true);49 expect(injector.has('xyz')).toBe(false);50 expect(injector.has('$injector')).toBe(true);51 });52 it('should provide useful message if no provider', function() {53 expect(function() {54 injector.get('idontexist');55 }).toThrowMinErr("$injector", "unpr", "Unknown provider: idontexistProvider <- idontexist");56 });57 it('should not corrupt the cache when an object fails to get instantiated', function() {58 expect(function() {59 injector.get('idontexist');60 }).toThrowMinErr("$injector", "unpr", "Unknown provider: idontexistProvider <- idontexist");61 expect(function() {62 injector.get('idontexist');63 }).toThrowMinErr("$injector", "unpr", "Unknown provider: idontexistProvider <- idontexist");64 });65 it('should provide path to the missing provider', function() {66 providers('a', function(idontexist) {return 1;});67 providers('b', function(a) {return 2;});68 expect(function() {69 injector.get('b');70 }).toThrowMinErr("$injector", "unpr", "Unknown provider: idontexistProvider <- idontexist <- a <- b");71 });72 it('should create a new $injector for the run phase', inject(function($injector) {73 expect($injector).not.toBe(providerInjector);74 }));75 describe('invoke', function() {76 var args;77 beforeEach(function() {78 args = null;79 providers('a', function() {return 1;});80 providers('b', function() {return 2;});81 });82 function fn(a, b, c, d) {83 /* jshint -W040 */84 args = [this, a, b, c, d];85 return a + b + c + d;86 }87 it('should call function', function() {88 fn.$inject = ['a', 'b', 'c', 'd'];89 injector.invoke(fn, {name:"this"}, {c:3, d:4});90 expect(args).toEqual([{name:'this'}, 1, 2, 3, 4]);91 });92 it('should treat array as annotations', function() {93 injector.invoke(['a', 'b', 'c', 'd', fn], {name:"this"}, {c:3, d:4});94 expect(args).toEqual([{name:'this'}, 1, 2, 3, 4]);95 });96 it('should invoke the passed-in fn with all of the dependencies as arguments', function() {97 providers('c', function() {return 3;});98 providers('d', function() {return 4;});99 expect(injector.invoke(['a', 'b', 'c', 'd', fn])).toEqual(10);100 });101 it('should fail with errors if not function or array', function() {102 expect(function() {103 injector.invoke({});104 }).toThrowMinErr("ng", "areq", "Argument 'fn' is not a function, got Object");105 expect(function() {106 injector.invoke(['a', 123], {});107 }).toThrowMinErr("ng", "areq", "Argument 'fn' is not a function, got number");108 });109 });110 describe('annotation', function() {111 /* global annotate: false */112 it('should return $inject', function() {113 function fn() {}114 fn.$inject = ['a'];115 expect(annotate(fn)).toBe(fn.$inject);116 expect(annotate(function() {})).toEqual([]);117 expect(annotate(function () {})).toEqual([]);118 expect(annotate(function () {})).toEqual([]);119 expect(annotate(function /* */ () {})).toEqual([]);120 });121 it('should create $inject', function() {122 var extraParans = angular.noop;123 // keep the multi-line to make sure we can handle it124 function $f_n0 /*125 */(126 $a, // x, <-- looks like an arg but it is a comment127 b_, /* z, <-- looks like an arg but it is a128 multi-line comment129 function (a, b) {}130 */131 _c,132 /* {some type} */ d) { extraParans();}133 expect(annotate($f_n0)).toEqual(['$a', 'b_', '_c', 'd']);134 expect($f_n0.$inject).toEqual(['$a', 'b_', '_c', 'd']);135 });136 it('should strip leading and trailing underscores from arg name during inference', function() {137 function beforeEachFn(_foo_) { /* foo = _foo_ */ }138 expect(annotate(beforeEachFn)).toEqual(['foo']);139 });140 it('should handle no arg functions', function() {141 function $f_n0() {}142 expect(annotate($f_n0)).toEqual([]);143 expect($f_n0.$inject).toEqual([]);144 });145 it('should handle no arg functions with spaces in the arguments list', function() {146 function fn( ) {}147 expect(annotate(fn)).toEqual([]);148 expect(fn.$inject).toEqual([]);149 });150 it('should handle args with both $ and _', function() {151 function $f_n0($a_) {}152 expect(annotate($f_n0)).toEqual(['$a_']);153 expect($f_n0.$inject).toEqual(['$a_']);154 });155 it('should throw on non function arg', function() {156 expect(function() {157 annotate({});158 }).toThrow();159 });160 it('should publish annotate API', function() {161 expect(injector.annotate).toBe(annotate);162 });163 });164 it('should have $injector', function() {165 var $injector = createInjector();166 expect($injector.get('$injector')).toBe($injector);167 });168 it('should define module', function() {169 var log = '';170 var injector = createInjector([function($provide) {171 $provide.value('value', 'value;');172 $provide.factory('fn', valueFn('function;'));173 $provide.provider('service', function() {174 this.$get = valueFn('service;');175 });176 }, function(valueProvider, fnProvider, serviceProvider) {177 log += valueProvider.$get() + fnProvider.$get() + serviceProvider.$get();178 }]).invoke(function(value, fn, service) {179 log += '->' + value + fn + service;180 });181 expect(log).toEqual('value;function;service;->value;function;service;');182 });183 describe('module', function() {184 it('should provide $injector even when no module is requested', function() {185 var $provide, $injector = createInjector([186 angular.extend(function(p) { $provide = p; }, {$inject: ['$provide']})187 ]);188 expect($injector.get('$injector')).toBe($injector);189 });190 it('should load multiple function modules and infer inject them', function() {191 var a = 'junk';192 var $injector = createInjector([193 function() {194 a = 'A'; // reset to prove we ran195 },196 function($provide) {197 $provide.value('a', a);198 },199 angular.extend(function(p, serviceA) {200 p.value('b', serviceA.$get() + 'B' );201 }, {$inject:['$provide', 'aProvider']}),202 ['$provide', 'bProvider', function(p, serviceB) {203 p.value('c', serviceB.$get() + 'C');204 }]205 ]);206 expect($injector.get('a')).toEqual('A');207 expect($injector.get('b')).toEqual('AB');208 expect($injector.get('c')).toEqual('ABC');209 });210 it('should run symbolic modules', function() {211 angularModule('myModule', []).value('a', 'abc');212 var $injector = createInjector(['myModule']);213 expect($injector.get('a')).toEqual('abc');214 });215 it('should error on invalid module name', function() {216 expect(function() {217 createInjector(['IDontExist'], {});218 }).toThrowMinErr('$injector', 'modulerr',219 /\[\$injector:nomod\] Module 'IDontExist' is not available! You either misspelled the module name or forgot to load it/);220 });221 it('should load dependant modules only once', function() {222 var log = '';223 angular.module('a', [], function(){ log += 'a'; });224 angular.module('b', ['a'], function(){ log += 'b'; });225 angular.module('c', ['a', 'b'], function(){ log += 'c'; });226 createInjector(['c', 'c']);227 expect(log).toEqual('abc');228 });229 it('should load different instances of dependent functions', function() {230 function generateValueModule(name, value) {231 return function ($provide) {232 $provide.value(name, value);233 };234 }235 var injector = createInjector([generateValueModule('name1', 'value1'),236 generateValueModule('name2', 'value2')]);237 expect(injector.get('name2')).toBe('value2');238 });239 it('should load same instance of dependent function only once', function() {240 var count = 0;241 function valueModule($provide) {242 count++;243 $provide.value('name', 'value');244 }245 var injector = createInjector([valueModule, valueModule]);246 expect(injector.get('name')).toBe('value');247 expect(count).toBe(1);248 });249 it('should execute runBlocks after injector creation', function() {250 var log = '';251 angular.module('a', [], function(){ log += 'a'; }).run(function() { log += 'A'; });252 angular.module('b', ['a'], function(){ log += 'b'; }).run(function() { log += 'B'; });253 createInjector([254 'b',255 valueFn(function() { log += 'C'; }),256 [valueFn(function() { log += 'D'; })]257 ]);258 expect(log).toEqual('abABCD');259 });260 describe('$provide', function() {261 it('should throw an exception if we try to register a service called "hasOwnProperty"', function() {262 createInjector([function($provide) {263 expect(function() {264 $provide.provider('hasOwnProperty', function() { });265 }).toThrowMinErr('ng', 'badname');266 }]);267 });268 it('should throw an exception if we try to register a constant called "hasOwnProperty"', function() {269 createInjector([function($provide) {270 expect(function() {271 $provide.constant('hasOwnProperty', {});272 }).toThrowMinErr('ng', 'badname');273 }]);274 });275 describe('constant', function() {276 it('should create configuration injectable constants', function() {277 var log = [];278 createInjector([279 function($provide){280 $provide.constant('abc', 123);281 $provide.constant({a: 'A', b:'B'});282 return function(a) {283 log.push(a);284 };285 },286 function(abc) {287 log.push(abc);288 return function(b) {289 log.push(b);290 };291 }292 ]).get('abc');293 expect(log).toEqual([123, 'A', 'B']);294 });295 });296 describe('value', function() {297 it('should configure $provide values', function() {298 expect(createInjector([function($provide) {299 $provide.value('value', 'abc');300 }]).get('value')).toEqual('abc');301 });302 it('should configure a set of values', function() {303 expect(createInjector([function($provide) {304 $provide.value({value: Array});305 }]).get('value')).toEqual(Array);306 });307 });308 describe('factory', function() {309 it('should configure $provide factory function', function() {310 expect(createInjector([function($provide) {311 $provide.factory('value', valueFn('abc'));312 }]).get('value')).toEqual('abc');313 });314 it('should configure a set of factories', function() {315 expect(createInjector([function($provide) {316 $provide.factory({value: Array});317 }]).get('value')).toEqual([]);318 });319 });320 describe('service', function() {321 it('should register a class', function() {322 var Type = function(value) {323 this.value = value;324 };325 var instance = createInjector([function($provide) {326 $provide.value('value', 123);327 $provide.service('foo', Type);328 }]).get('foo');329 expect(instance instanceof Type).toBe(true);330 expect(instance.value).toBe(123);331 });332 it('should register a set of classes', function() {333 var Type = function() {};334 var injector = createInjector([function($provide) {335 $provide.service({336 foo: Type,337 bar: Type338 });339 }]);340 expect(injector.get('foo') instanceof Type).toBe(true);341 expect(injector.get('bar') instanceof Type).toBe(true);342 });343 });344 describe('provider', function() {345 it('should configure $provide provider object', function() {346 expect(createInjector([function($provide) {347 $provide.provider('value', {348 $get: valueFn('abc')349 });350 }]).get('value')).toEqual('abc');351 });352 it('should configure $provide provider type', function() {353 function Type() {}354 Type.prototype.$get = function() {355 expect(this instanceof Type).toBe(true);356 return 'abc';357 };358 expect(createInjector([function($provide) {359 $provide.provider('value', Type);360 }]).get('value')).toEqual('abc');361 });362 it('should configure $provide using an array', function() {363 function Type(PREFIX) {364 this.prefix = PREFIX;365 }366 Type.prototype.$get = function() {367 return this.prefix + 'def';368 };369 expect(createInjector([function($provide) {370 $provide.constant('PREFIX', 'abc');371 $provide.provider('value', ['PREFIX', Type]);372 }]).get('value')).toEqual('abcdef');373 });374 it('should configure a set of providers', function() {375 expect(createInjector([function($provide) {376 $provide.provider({value: valueFn({$get:Array})});377 }]).get('value')).toEqual([]);378 });379 });380 describe('decorator', function() {381 var log, injector;382 beforeEach(function() {383 log = [];384 });385 it('should be called with the original instance', function() {386 injector = createInjector([function($provide) {387 $provide.value('myService', function(val) {388 log.push('myService:' + val);389 return 'origReturn';390 });391 $provide.decorator('myService', function($delegate) {392 return function(val) {393 log.push('myDecoratedService:' + val);394 var origVal = $delegate('decInput');395 return 'dec+' + origVal;396 };397 });398 }]);399 var out = injector.get('myService')('input');400 log.push(out);401 expect(log.join('; ')).402 toBe('myDecoratedService:input; myService:decInput; dec+origReturn');403 });404 it('should allow multiple decorators to be applied to a service', function() {405 injector = createInjector([function($provide) {406 $provide.value('myService', function(val) {407 log.push('myService:' + val);408 return 'origReturn';409 });410 $provide.decorator('myService', function($delegate) {411 return function(val) {412 log.push('myDecoratedService1:' + val);413 var origVal = $delegate('decInput1');414 return 'dec1+' + origVal;415 };416 });417 $provide.decorator('myService', function($delegate) {418 return function(val) {419 log.push('myDecoratedService2:' + val);420 var origVal = $delegate('decInput2');421 return 'dec2+' + origVal;422 };423 });424 }]);425 var out = injector.get('myService')('input');426 log.push(out);427 expect(log).toEqual(['myDecoratedService2:input',428 'myDecoratedService1:decInput2',429 'myService:decInput1',430 'dec2+dec1+origReturn']);431 });432 it('should decorate services with dependencies', function() {433 injector = createInjector([function($provide) {434 $provide.value('dep1', 'dependency1');435 $provide.factory('myService', ['dep1', function(dep1) {436 return function(val) {437 log.push('myService:' + val + ',' + dep1);438 return 'origReturn';439 };440 }]);441 $provide.decorator('myService', function($delegate) {442 return function(val) {443 log.push('myDecoratedService:' + val);444 var origVal = $delegate('decInput');445 return 'dec+' + origVal;446 };447 });448 }]);449 var out = injector.get('myService')('input');450 log.push(out);451 expect(log.join('; ')).452 toBe('myDecoratedService:input; myService:decInput,dependency1; dec+origReturn');453 });454 it('should allow for decorators to be injectable', function() {455 injector = createInjector([function($provide) {456 $provide.value('dep1', 'dependency1');457 $provide.factory('myService', function() {458 return function(val) {459 log.push('myService:' + val);460 return 'origReturn';461 };462 });463 $provide.decorator('myService', function($delegate, dep1) {464 return function(val) {465 log.push('myDecoratedService:' + val + ',' + dep1);466 var origVal = $delegate('decInput');467 return 'dec+' + origVal;468 };469 });470 }]);471 var out = injector.get('myService')('input');472 log.push(out);473 expect(log.join('; ')).474 toBe('myDecoratedService:input,dependency1; myService:decInput; dec+origReturn');475 });476 });477 });478 describe('error handling', function() {479 it('should handle wrong argument type', function() {480 expect(function() {481 createInjector([482 {}483 ], {});484 }).toThrowMinErr('$injector', 'modulerr', /Failed to instantiate module \{\} due to:\n.*\[ng:areq\] Argument 'module' is not a function, got Object/);485 });486 it('should handle exceptions', function() {487 expect(function() {488 createInjector([function() {489 throw 'MyError';490 }], {});491 }).toThrowMinErr('$injector', 'modulerr', /Failed to instantiate module .+ due to:\n.*MyError/);492 });493 it('should decorate the missing service error with module name', function() {494 angular.module('TestModule', [], function(xyzzy) {});495 expect(function() {496 createInjector(['TestModule' ]);497 }).toThrowMinErr(498 '$injector', 'modulerr', /Failed to instantiate module TestModule due to:\n.*\[\$injector:unpr] Unknown provider: xyzzy/499 );500 });501 it('should decorate the missing service error with module function', function() {502 function myModule(xyzzy){}503 expect(function() {504 createInjector([myModule]);505 }).toThrowMinErr(506 '$injector', 'modulerr', /Failed to instantiate module function myModule\(xyzzy\) due to:\n.*\[\$injector:unpr] Unknown provider: xyzzy/507 );508 });509 it('should decorate the missing service error with module array function', function() {510 function myModule(xyzzy){}511 expect(function() {512 createInjector([['xyzzy', myModule]]);513 }).toThrowMinErr(514 '$injector', 'modulerr', /Failed to instantiate module function myModule\(xyzzy\) due to:\n.*\[\$injector:unpr] Unknown provider: xyzzy/515 );516 });517 it('should throw error when trying to inject oneself', function() {518 expect(function() {519 createInjector([function($provide){520 $provide.factory('service', function(service){});521 return function(service) {};522 }]);523 }).toThrowMinErr('$injector', 'cdep', 'Circular dependency found: service <- service');524 });525 it('should throw error when trying to inject circular dependency', function() {526 expect(function() {527 createInjector([function($provide){528 $provide.factory('a', function(b){});529 $provide.factory('b', function(a){});530 return function(a) {};531 }]);532 }).toThrowMinErr('$injector', 'cdep', 'Circular dependency found: a <- b <- a');533 });534 });535 });536 describe('retrieval', function() {537 var instance = {name:'angular'};538 var Instance = function() { this.name = 'angular'; };539 function createInjectorWithValue(instanceName, instance) {540 return createInjector([ ['$provide', function(provide) {541 provide.value(instanceName, instance);542 }]]);543 }544 function createInjectorWithFactory(serviceName, serviceDef) {545 return createInjector([ ['$provide', function(provide) {546 provide.factory(serviceName, serviceDef);547 }]]);548 }549 it('should retrieve by name', function() {550 var $injector = createInjectorWithValue('instance', instance);551 var retrievedInstance = $injector.get('instance');552 expect(retrievedInstance).toBe(instance);553 });554 it('should cache instance', function() {555 var $injector = createInjectorWithFactory('instance', function() { return new Instance(); });556 var instance = $injector.get('instance');557 expect($injector.get('instance')).toBe(instance);558 expect($injector.get('instance')).toBe(instance);559 });560 it('should call functions and infer arguments', function() {561 var $injector = createInjectorWithValue('instance', instance);562 expect($injector.invoke(function(instance) { return instance; })).toBe(instance);563 });564 });565 describe('method invoking', function() {566 var $injector;567 beforeEach(function() {568 $injector = createInjector([ function($provide) {569 $provide.value('book', 'moby');570 $provide.value('author', 'melville');571 }]);572 });573 it('should invoke method', function() {574 expect($injector.invoke(function(book, author) {575 return author + ':' + book;576 })).toEqual('melville:moby');577 expect($injector.invoke(function(book, author) {578 expect(this).toEqual($injector);579 return author + ':' + book;580 }, $injector)).toEqual('melville:moby');581 });582 it('should invoke method with locals', function() {583 expect($injector.invoke(function(book, author) {584 return author + ':' + book;585 })).toEqual('melville:moby');586 expect($injector.invoke(587 function(book, author, chapter) {588 expect(this).toEqual($injector);589 return author + ':' + book + '-' + chapter;590 }, $injector, {author:'m', chapter:'ch1'})).toEqual('m:moby-ch1');591 });592 it('should invoke method which is annotated', function() {593 expect($injector.invoke(extend(function(b, a) {594 return a + ':' + b;595 }, {$inject:['book', 'author']}))).toEqual('melville:moby');596 expect($injector.invoke(extend(function(b, a) {597 expect(this).toEqual($injector);598 return a + ':' + b;599 }, {$inject:['book', 'author']}), $injector)).toEqual('melville:moby');600 });601 it('should invoke method which is an array of annotation', function() {602 expect($injector.invoke(function(book, author) {603 return author + ':' + book;604 })).toEqual('melville:moby');605 expect($injector.invoke(function(book, author) {606 expect(this).toEqual($injector);607 return author + ':' + book;608 }, $injector)).toEqual('melville:moby');609 });610 it('should throw usefull error on wrong argument type]', function() {611 expect(function() {612 $injector.invoke({});613 }).toThrowMinErr("ng", "areq", "Argument 'fn' is not a function, got Object");614 });615 });616 describe('service instantiation', function() {617 var $injector;618 beforeEach(function() {619 $injector = createInjector([ function($provide) {620 $provide.value('book', 'moby');621 $provide.value('author', 'melville');622 }]);623 });624 function Type(book, author) {625 this.book = book;626 this.author = author;627 }628 Type.prototype.title = function() {629 return this.author + ': ' + this.book;630 };631 it('should instantiate object and preserve constructor property and be instanceof', function() {632 var t = $injector.instantiate(Type);633 expect(t.book).toEqual('moby');634 expect(t.author).toEqual('melville');635 expect(t.title()).toEqual('melville: moby');636 expect(t instanceof Type).toBe(true);637 });638 it('should instantiate object and preserve constructor property and be instanceof ' +639 'with the array annotated type', function() {640 var t = $injector.instantiate(['book', 'author', Type]);641 expect(t.book).toEqual('moby');642 expect(t.author).toEqual('melville');643 expect(t.title()).toEqual('melville: moby');644 expect(t instanceof Type).toBe(true);645 });646 it('should allow constructor to return different object', function() {647 var obj = {};648 var Class = function() {649 return obj;650 };651 expect($injector.instantiate(Class)).toBe(obj);652 });653 it('should allow constructor to return a function', function() {654 var fn = function() {};655 var Class = function() {656 return fn;657 };658 expect($injector.instantiate(Class)).toBe(fn);659 });660 it('should handle constructor exception', function() {661 expect(function() {662 $injector.instantiate(function() { throw 'MyError'; });663 }).toThrow('MyError');664 });665 it('should return instance if constructor returns non-object value', function() {666 var A = function() {667 return 10;668 };669 var B = function() {670 return 'some-string';671 };672 var C = function() {673 return undefined;674 };675 expect($injector.instantiate(A) instanceof A).toBe(true);676 expect($injector.instantiate(B) instanceof B).toBe(true);677 expect($injector.instantiate(C) instanceof C).toBe(true);678 });679 });680 describe('protection modes', function() {681 it('should prevent provider lookup in app', function() {682 var $injector = createInjector([function($provide) {683 $provide.value('name', 'angular');684 }]);685 expect(function() {686 $injector.get('nameProvider');687 }).toThrowMinErr("$injector", "unpr", "Unknown provider: nameProviderProvider <- nameProvider");688 });689 it('should prevent provider configuration in app', function() {690 var $injector = createInjector([]);691 expect(function() {692 $injector.get('$provide').value('a', 'b');693 }).toThrowMinErr("$injector", "unpr", "Unknown provider: $provideProvider <- $provide");694 });695 it('should prevent instance lookup in module', function() {696 function instanceLookupInModule(name) { throw new Error('FAIL'); }697 expect(function() {698 createInjector([function($provide) {699 $provide.value('name', 'angular');700 }, instanceLookupInModule]);701 }).toThrowMatching(/\[\$injector:unpr] Unknown provider: name/);702 });703 });...
injector.spec.ts
Source:injector.spec.ts
1import { Injector } from "www/injector";2class Counter {3 private count = 0;4 increment() {5 this.count++;6 }7 get() {8 return this.count;9 }10}11class CounterMock extends Counter {12 get() {13 return 3;14 }15}16class MaxOccupancy {17 private counter: Counter;18 constructor(injector: Injector) {19 this.counter = injector.get(Counter);20 }21 isReached() {22 return this.counter.get() > 2;23 }24}25test("Inject one symbol", () => {26 const injector = new Injector();27 injector.register(Counter);28 const counter = injector.get(Counter);29 counter.increment();30 expect(counter.get()).toEqual(1);31});32test("Mock one symbol", () => {33 const injector = new Injector();34 injector.register(Counter);35 injector.register(Counter, CounterMock);36 const counter = injector.get(Counter);37 counter.increment();38 expect(counter.get()).toEqual(3);39});40test("Inject the injector", () => {41 const injector = new Injector();42 injector.register(Counter);43 injector.register(MaxOccupancy);44 const maxOccupancy = injector.get(MaxOccupancy);45 expect(maxOccupancy.isReached()).toEqual(false);46});47test("Do not instance twice", () => {48 const injector = new Injector();49 injector.register(Counter);50 const counterA = injector.get(Counter);51 const counterB = injector.get(Counter);52 counterA.increment();53 expect(counterA.get()).toEqual(1);54 expect(counterB.get()).toEqual(1);55 expect(counterA).toBe(counterB);56});57class Value {58 n: number = 0;59}60function makeValue(n: number): new () => Value {61 return class extends Value {62 n: number = n;63 };64}65test("Inject a list", () => {66 const injector = new Injector();67 injector.register(Value, makeValue(1));68 injector.register(Value, makeValue(2));69 injector.register(Value, makeValue(3));70 const values = injector.list(Value);71 expect(values).toMatchObject([{ n: 1 }, { n: 2 }, { n: 3 }]);72});73test("Do not instance the same list twice", () => {74 const injector = new Injector();75 injector.register(Value, makeValue(1));76 injector.register(Value, makeValue(2));77 injector.register(Value, makeValue(3));78 const values1 = injector.list(Value);79 const values2 = injector.list(Value);80 expect(values1).toBe(values2);81});82test("Configures the injector", () => {83 let foundInjector;84 const injector = new Injector();85 const result = injector.configure(function (configuringInjector) {86 configuringInjector.register(Counter);87 foundInjector = configuringInjector;88 });89 const counter = injector.get(Counter);90 expect(counter.get()).toBe(0);91 expect(foundInjector).toBe(injector);92 expect(result).toBe(injector);93});94test("Manually set a value", () => {95 const myCounter = new Counter();96 const injector = new Injector();97 injector.set(Counter, myCounter);98 const counter = injector.get(Counter);99 expect(counter).toBe(myCounter);100});101test("Throws a comprehensible exception when trying to get a symbol without register", () => {102 const injector = new Injector();103 expect(() => injector.get(Counter)).toThrow(/No Counter registered/);104});105test("The same type can satisfy two injections but it is instantiated once", () => {106 class A {107 a() {}108 }109 class B {110 b() {}111 }112 class C implements A, B {113 a() {}114 b() {}115 c() {}116 }117 const injector = new Injector();118 injector.register(A, C);119 injector.register(B, C);120 injector.register(C, C);121 const a = injector.get(A);122 const b = injector.get(B);123 const c = injector.get(C);124 expect(a).toBe(b);125 expect(a).toBe(c);...
controllers.js
Source:controllers.js
1define(['angular', 'services'], function (angular) {2 'use strict';3 return angular.module('myApp.controllers', ['myApp.services'])4 .controller('HomeCtrl', ['$scope', '$injector', function ($scope, $injector) {5 require(['../feature/home/homeController'], function (controller) {6 $injector.invoke(controller, this, {'$scope': $scope});7 });8 }])9 .controller('appSelectorController', ['$scope', '$injector', function ($scope, $injector) {10 require(['../feature/appInfo/appSelectorController'], function (controller) {11 $injector.invoke(controller, this, {'$scope': $scope});12 });13 }])14 .controller('appDetailController', ['$scope', '$injector', function ($scope, $injector) {15 require(['../feature/appInfo/appDetailController'], function (controller) {16 $injector.invoke(controller, this, {'$scope': $scope});17 });18 }])19 .controller('forcedGraphCtrl', ['$scope', '$injector', function ($scope, $injector) {20 require(['../feature/dependencyGraph/forcedGraphController'], function (controller) {21 $injector.invoke(controller, this, {'$scope': $scope});22 });23 }])24 .controller('changeEventsCtrl', ['$scope', '$injector', function ($scope, $injector) {25 require(['../feature/janus/changeEventsController'], function (controller) {26 $injector.invoke(controller, this, {'$scope': $scope});27 });28 }])29 .controller('maintenanceEventsCtrl', ['$scope', '$injector', function ($scope, $injector) {30 require(['../feature/janus/maintenanceEventsController'], function (controller) {31 $injector.invoke(controller, this, {'$scope': $scope});32 });33 }])34 .controller('dataCenterControllers', ['$scope', '$injector', function ($scope, $injector) {35 require(['../feature/data_centers/dataCenterControllers'], function (controller) {36 $injector.invoke(controller, this, {'$scope': $scope});37 });38 }]);...
Using AI Code Generation
1import { Injector } from '@angular/core';2import { MockBuilder, MockRender, ngMocks } from 'ng-mocks';3import { MyComponent } from './my.component';4import { MyModule } from './my.module';5describe('MyComponent', () => {6 beforeEach(() => MockBuilder(MyComponent).keep(MyModule));7 it('should render', () => {8 const fixture = MockRender(MyComponent);9 expect(fixture.point.componentInstance).toBeDefined();10 });11 it('should inject', () => {12 const fixture = MockRender(MyComponent);13 const injector = ngMocks.get(fixture.point.componentInstance, Injector);14 expect(injector).toBeDefined();15 });16});17import { Component } from '@angular/core';18@Component({19})20export class MyComponent {}21import { NgModule } from '@angular/core';22import { MyComponent } from './my.component';23@NgModule({24})25export class MyModule {}26I am using the ng-mocks library to mock the Angular component. My component uses the @Injectable() decorator to inject the service into the component. I am using the ngMocks.get() method to get the injector of the component. I am getting the error “Cannot read property ‘injector’ of undefined” when I am using the ngMocks.get() method. Can anyone help me to resolve this issue?27I am using the ng-mocks library to mock the Angular component. My component uses the @Injectable() decorator to inject the service into the component. I am using the ngMocks.get() method to get the injector of the component. I am getting the error “Cannot read property ‘injector’ of undefined” when I am using the ngMocks.get() method. Can anyone help me to resolve this issue?28I am using the ng-mocks library to mock the Angular component. My component uses the @Injectable() decorator to inject the service into the component. I am using the ngMocks.get() method to get the injector of the component. I am getting the error “Cannot read property ‘injector’ of undefined” when I am using the ngMocks.get() method
Using AI Code Generation
1import {Injector} from '@angular/core';2import {TestBed} from '@angular/core/testing';3import {MockBuilder, MockRender, MockReset} from 'ng-mocks';4import {MyComponent} from './my.component';5import {MyService} from './my.service';6import {MyServiceMock} from './my.service.mock';7describe('MyComponent', () => {8 beforeEach(() => MockBuilder(MyComponent, MyService));9 afterEach(() => MockReset());10 it('should create', () => {11 const injector = Injector.create({12 {13 useValue: new MyServiceMock(),14 },15 });16 MockRender(MyComponent, undefined, injector);17 expect(TestBed.inject(MyService)).toBeInstanceOf(MyServiceMock);18 });19});20import {MyService} from './my.service';21export class MyServiceMock extends MyService {22 public getMyValue(): string {23 return 'mocked value';24 }25}26import {Injectable} from '@angular/core';27@Injectable()28export class MyService {29 public getMyValue(): string {30 return 'real value';31 }32}33import {Component} from '@angular/core';34import {MyService} from './my.service';35@Component({36 template: `{{myValue}}`,37})38export class MyComponent {39 public myValue: string;40 constructor(private readonly myService: MyService) {41 this.myValue = this.myService.getMyValue();42 }43}44import {TestBed} from '@angular/core/testing';45import {MyComponent} from './my.component';46import {MyService} from './my.service';47import {MyServiceMock} from './my.service.mock';48describe('MyComponent', () => {49 beforeEach(() => {50 TestBed.configureTestingModule({51 {52 useValue: new MyServiceMock(),53 },54 });55 });56 it('should create', () => {57 const fixture = TestBed.createComponent(MyComponent);58 expect(fixture.componentInstance).toBeTruthy();59 });60});
Using AI Code Generation
1import {Injector} from '@angular/core';2import {TestBed} from '@angular/core/testing';3import {RouterTestingModule} from '@angular/router/testing';4import {Router} from '@angular/router';5import {RouterMock} from './router-mock';6describe('RouterMock', () => {7 let router;8 beforeEach(() => {9 TestBed.configureTestingModule({10 imports: [RouterTestingModule],11 {12 useFactory: () => RouterMock,13 },14 });15 router = Injector.get(Router);16 });17 it('should be created', () => {18 expect(router).toBeTruthy();19 });20});21import {Router} from '@angular/router';22export const RouterMock = {23 navigate: jasmine.createSpy('navigate'),24 navigateByUrl: jasmine.createSpy('navigateByUrl'),25 serializeUrl: jasmine.createSpy('serializeUrl'),26 parseUrl: jasmine.createSpy('parseUrl'),27 isActive: jasmine.createSpy('isActive'),28};29import {RouterMock} from './router-mock';30describe('RouterMock', () => {31 it('should be created', () => {32 expect(RouterMock).toBeTruthy();33 });34 it('should have navigate function', () => {35 expect(RouterMock.navigate).toBeTruthy();36 });37 it('should have navigateByUrl function', () => {38 expect(RouterMock.navigateByUrl).toBeTruthy();39 });40 it('should have serializeUrl function', () => {41 expect(RouterMock.serializeUrl).toBeTruthy();42 });43 it('should have parseUrl function', () => {44 expect(RouterMock.parseUrl).toBeTruthy();45 });46 it('should have isActive function', () => {47 expect(RouterMock.isActive).toBeTruthy();48 });49});50declare module '@angular/router' {51 export interface Router {52 navigate: jasmine.Spy;53 navigateByUrl: jasmine.Spy;54 serializeUrl: jasmine.Spy;55 parseUrl: jasmine.Spy;56 isActive: jasmine.Spy;57 }58}59{60 "compilerOptions": {
Using AI Code Generation
1describe('Test Component', () => {2 beforeEach(() => {3 TestBed.configureTestingModule({4 imports: [RouterTestingModule]5 });6 TestBed.overrideComponent(TestComponent, {7 set: {8 template: `{{componentName}}`9 }10 });11 TestBed.compileComponents();12 });13 it('should create the app', async(() => {14 const fixture = TestBed.createComponent(TestComponent);15 const app = fixture.debugElement.componentInstance;16 expect(app).toBeTruthy();17 }));18 it('should render title in a h1 tag', async(() => {19 const fixture = TestBed.createComponent(TestComponent);20 fixture.detectChanges();21 const compiled = fixture.debugElement.nativeElement;22 expect(compiled.querySelector('h1').textContent).toContain('Welcome to app!');23 }));24});25import { Component, OnInit } from '@angular/core';26import { Router } from '@angular/router';27@Component({28})29export class TestComponent implements OnInit {30 componentName: string;31 constructor(private router: Router) { }32 ngOnInit() {33 this.componentName = this.router.url;34 }35}36 {{componentName}}37/* You can add global styles to this file, and also import other style files */38h1 {39 color: #369;40 font-family: Arial, Helvetica, sans-serif;41 font-size: 250%;42}43import { async, ComponentFixture, TestBed } from '@angular/core/testing';44import { TestComponent } from './test.component';45describe('TestComponent', () => {46 let component: TestComponent;47 let fixture: ComponentFixture<TestComponent>;48 beforeEach(async(() => {49 TestBed.configureTestingModule({50 })51 .compileComponents();52 }));53 beforeEach(() => {54 fixture = TestBed.createComponent(TestComponent);55 component = fixture.componentInstance;56 fixture.detectChanges();57 });58 it('should create', () => {59 expect(component).toBeTruthy();60 });61});62import { BrowserModule } from '@angular/platform-browser';63import { NgModule } from '@angular/core';64import { AppComponent } from './app.component';65import { TestComponent } from './test/test.component';66import { RouterModule, Routes } from '@
Using AI Code Generation
1import {ngMocks} from 'ng-mocks';2const injector = ngMocks.default;3const injector = ngMocks.default();4const injector = ngMocks.default.get();5const injector = ngMocks.default.get(ngMocks.default);6const injector = ngMocks.default.get(ngMocks.default.get());7const injector = ngMocks.default.get(ngMocks.default.get(ngMocks.default));8const injector = ngMocks.default.get(ngMocks.default.get(ngMocks.default.get()));9const injector = ngMocks.default.get(ngMocks.default.get(ngMocks.default.get(ngMocks.default)));10const injector = ngMocks.default.get(ngMocks.default.get(ngMocks.default.get(ngMocks.default.get())));11const injector = ngMocks.default.get(ngMocks.default.get(ngMocks.default.get(ngMocks.default.get(ngMocks.default))));12const injector = ngMocks.default.get(ngMocks.default.get(ngMocks.default.get(ngMocks.default.get(ngMocks.default.get()))));13const injector = ngMocks.default.get(ngMocks.default.get(ngMocks.default.get(ngMocks.default.get(ngMocks.default.get(ngMocks.default)))));14const injector = ngMocks.default.get(ngMocks.default.get(ngMocks.default.get(ngMocks.default.get(ngMocks.default.get(ngMocks.default.get())))));15const injector = ngMocks.default.get(ngMocks.default.get(ngMocks.default.get(ngMocks.default.get(ngMocks.default.get(ngMocks.default.get(ngMocks.default))))));16const injector = ngMocks.default.get(ngMocks.default.get(ngMocks.default.get(ngMocks.default.get(ngMocks.default.get(ngMocks.default.get(
Using AI Code Generation
1import { TestBed } from '@angular/core/testing';2import { AppComponent } from './app.component';3import { RouterTestingModule } from '@angular/router/testing';4import { MockBuilder, MockRender } from 'ng-mocks';5import { MyService } from './my.service';6import { MyServiceMock } from './my.service.mock';7describe('AppComponent', () => {8 beforeEach(() => MockBuilder(AppComponent, RouterTestingModule));9 it('should create the app', () => {10 const fixture = MockRender(AppComponent);11 const app = fixture.point.componentInstance;12 expect(app).toBeTruthy();13 });14 it('should have as title "ng-mocks-test"', () => {15 const fixture = MockRender(AppComponent);16 const app = fixture.point.componentInstance;17 expect(app.title).toEqual('ng-mocks-test');18 });19 it('should render title', () => {20 const fixture = MockRender(AppComponent);21 fixture.detectChanges();22 const compiled = fixture.point.nativeElement;23 expect(compiled.querySelector('.content span').textContent).toContain(24 );25 });26 it('should call the service', () => {27 const fixture = MockRender(AppComponent);28 const app = fixture.point.componentInstance;29 app.ngOnInit();30 expect(app.myService.get()).toEqual('Hello World!');31 });32 it('should use the mock service', () => {33 const fixture = MockRender(AppComponent);34 const app = fixture.point.componentInstance;35 const myService = TestBed.inject(MyService);36 spyOn(myService, 'get').and.returnValue('Hello Mock!');37 app.ngOnInit();38 expect(app.myService.get()).toEqual('Hello Mock!');39 });40 it('should use the mock service with MockInstance', () => {41 const fixture = MockRender(AppComponent);42 const app = fixture.point.componentInstance;43 const myService = TestBed.inject(MyService);44 MockInstance(myService, 'get', 'Hello Mock!');45 app.ngOnInit();46 expect(app.myService.get()).toEqual('Hello Mock!');47 });48 it('should use the mock service with MockService', () => {49 const fixture = MockRender(AppComponent
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!