当前位置: 首页>>代码示例>>TypeScript>>正文


TypeScript testing_internal.inject函数代码示例

本文整理汇总了TypeScript中@angular/core/testing/testing_internal.inject函数的典型用法代码示例。如果您正苦于以下问题:TypeScript inject函数的具体用法?TypeScript inject怎么用?TypeScript inject使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了inject函数的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。

示例1: describe

  describe("MessageBus", () => {
    var bus: MessageBus;

    beforeEach(() => { bus = createConnectedMessageBus(); });

    it("should pass messages in the same channel from sink to source",
       inject([AsyncTestCompleter], (async) => {
         const CHANNEL = "CHANNEL 1";
         const MESSAGE = "Test message";
         bus.initChannel(CHANNEL, false);

         var fromEmitter = bus.from(CHANNEL);
         ObservableWrapper.subscribe(fromEmitter, (message: any) => {
           expect(message).toEqual(MESSAGE);
           async.done();
         });
         var toEmitter = bus.to(CHANNEL);
         ObservableWrapper.callEmit(toEmitter, MESSAGE);
       }));

    it("should broadcast", inject([AsyncTestCompleter], (async) => {
         const CHANNEL = "CHANNEL 1";
         const MESSAGE = "TESTING";
         const NUM_LISTENERS = 2;
         bus.initChannel(CHANNEL, false);

         var callCount = 0;
         var emitHandler = (message: any) => {
           expect(message).toEqual(MESSAGE);
           callCount++;
           if (callCount == NUM_LISTENERS) {
             async.done();
           }
         };

         for (var i = 0; i < NUM_LISTENERS; i++) {
           var emitter = bus.from(CHANNEL);
           ObservableWrapper.subscribe(emitter, emitHandler);
         }

         var toEmitter = bus.to(CHANNEL);
         ObservableWrapper.callEmit(toEmitter, MESSAGE);
       }));

    it("should keep channels independent", inject([AsyncTestCompleter], (async) => {
         const CHANNEL_ONE = "CHANNEL 1";
         const CHANNEL_TWO = "CHANNEL 2";
         const MESSAGE_ONE = "This is a message on CHANNEL 1";
         const MESSAGE_TWO = "This is a message on CHANNEL 2";
         var callCount = 0;
         bus.initChannel(CHANNEL_ONE, false);
         bus.initChannel(CHANNEL_TWO, false);

         var firstFromEmitter = bus.from(CHANNEL_ONE);
         ObservableWrapper.subscribe(firstFromEmitter, (message) => {
           expect(message).toEqual(MESSAGE_ONE);
           callCount++;
           if (callCount == 2) {
             async.done();
           }
         });
         var secondFromEmitter = bus.from(CHANNEL_TWO);
         ObservableWrapper.subscribe(secondFromEmitter, (message) => {
           expect(message).toEqual(MESSAGE_TWO);
           callCount++;
           if (callCount == 2) {
             async.done();
           }
         });

         var firstToEmitter = bus.to(CHANNEL_ONE);
         ObservableWrapper.callEmit(firstToEmitter, MESSAGE_ONE);

         var secondToEmitter = bus.to(CHANNEL_TWO);
         ObservableWrapper.callEmit(secondToEmitter, MESSAGE_TWO);
       }));
  });
开发者ID:Coco-wan,项目名称:angular,代码行数:77,代码来源:message_bus_spec.ts

示例2: describe

    describe('NgZone callback logic', () => {
      it('should fire whenstable callback if event is already finished',
         inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
           ngZone.unstable();
           ngZone.stable();
           testability.whenStable(execute);

           microTask(() => {
             expect(execute).toHaveBeenCalled();
             async.done();
           });
         }));

      it('should not fire whenstable callbacks synchronously if event is already finished', () => {
        ngZone.unstable();
        ngZone.stable();
        testability.whenStable(execute);

        expect(execute).not.toHaveBeenCalled();
      });

      it('should fire whenstable callback when event finishes',
         inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
           ngZone.unstable();
           testability.whenStable(execute);

           microTask(() => {
             expect(execute).not.toHaveBeenCalled();
             ngZone.stable();

             microTask(() => {
               expect(execute).toHaveBeenCalled();
               async.done();
             });
           });
         }));

      it('should not fire whenstable callbacks synchronously when event finishes', () => {
        ngZone.unstable();
        testability.whenStable(execute);
        ngZone.stable();

        expect(execute).not.toHaveBeenCalled();
      });

      it('should not fire whenstable callback when event did not finish',
         inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
           ngZone.unstable();
           testability.increasePendingRequestCount();
           testability.whenStable(execute);

           microTask(() => {
             expect(execute).not.toHaveBeenCalled();
             testability.decreasePendingRequestCount();

             microTask(() => {
               expect(execute).not.toHaveBeenCalled();
               ngZone.stable();

               microTask(() => {
                 expect(execute).toHaveBeenCalled();
                 async.done();
               });
             });
           });
         }));

      it('should not fire whenstable callback when there are pending counts',
         inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
           ngZone.unstable();
           testability.increasePendingRequestCount();
           testability.increasePendingRequestCount();
           testability.whenStable(execute);

           microTask(() => {
             expect(execute).not.toHaveBeenCalled();
             ngZone.stable();

             microTask(() => {
               expect(execute).not.toHaveBeenCalled();
               testability.decreasePendingRequestCount();

               microTask(() => {
                 expect(execute).not.toHaveBeenCalled();
                 testability.decreasePendingRequestCount();

                 microTask(() => {
                   expect(execute).toHaveBeenCalled();
                   async.done();
                 });
               });
             });
           });
         }));

      it('should fire whenstable callback with didWork if event is already finished',
         inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
           ngZone.unstable();
           ngZone.stable();
           testability.whenStable(execute);
//.........这里部分代码省略.........
开发者ID:AlmogShaul,项目名称:angular,代码行数:101,代码来源:testability_spec.ts

示例3: describe

  describe('regressions', () => {

    describe('platform pipes', () => {
      beforeEach(() => {
        TestBed.configureCompiler({useJit: useJit});
        TestBed.configureTestingModule({declarations: [PlatformPipe]});
      });

      it('should overwrite them by custom pipes',
         inject(
             [TestComponentBuilder, AsyncTestCompleter],
             (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
               tcb.overrideView(
                      MyComp1,
                      new ViewMetadata({template: '{{true | somePipe}}', pipes: [CustomPipe]}))
                   .createAsync(MyComp1)
                   .then((fixture) => {
                     fixture.detectChanges();
                     expect(fixture.nativeElement).toHaveText('someCustomPipe');
                     async.done();
                   });
             }));
    });

    describe('expressions', () => {

      it('should evaluate conditional and boolean operators with right precedence - #8244',
         inject(
             [TestComponentBuilder, AsyncTestCompleter],
             (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
               tcb.overrideView(
                      MyComp1, new ViewMetadata({template: `{{'red' + (true ? ' border' : '')}}`}))
                   .createAsync(MyComp1)
                   .then((fixture) => {
                     fixture.detectChanges();
                     expect(fixture.nativeElement).toHaveText('red border');
                     async.done();
                   });
             }));

      it('should evaluate conditional and unary operators with right precedence - #8235',
         inject(
             [TestComponentBuilder, AsyncTestCompleter],
             (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
               tcb.overrideView(MyComp1, new ViewMetadata({template: `{{!null?.length}}`}))
                   .createAsync(MyComp1)
                   .then((fixture) => {
                     fixture.detectChanges();
                     expect(fixture.nativeElement).toHaveText('true');
                     async.done();
                   });
             }));
    });

    describe('providers', () => {
      function createInjector(tcb: TestComponentBuilder, proviers: any[]): Promise<Injector> {
        return tcb.overrideProviders(MyComp1, [proviers])
            .createAsync(MyComp1)
            .then((fixture) => fixture.componentInstance.injector);
      }

      it('should support providers with an OpaqueToken that contains a `.` in the name',
         inject(
             [TestComponentBuilder, AsyncTestCompleter],
             (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
               var token = new OpaqueToken('a.b');
               var tokenValue = 1;
               createInjector(tcb, [
                 {provide: token, useValue: tokenValue}
               ]).then((injector: Injector) => {
                 expect(injector.get(token)).toEqual(tokenValue);
                 async.done();
               });
             }));

      it('should support providers with string token with a `.` in it',
         inject(
             [TestComponentBuilder, AsyncTestCompleter],
             (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
               var token = 'a.b';
               var tokenValue = 1;
               createInjector(tcb, [
                 {provide: token, useValue: tokenValue}
               ]).then((injector: Injector) => {
                 expect(injector.get(token)).toEqual(tokenValue);
                 async.done();
               });
             }));

      it('should support providers with an anonymous function',
         inject(
             [TestComponentBuilder, AsyncTestCompleter],
             (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
               var token = () => true;
               var tokenValue = 1;
               createInjector(tcb, [
                 {provide: token, useValue: tokenValue}
               ]).then((injector: Injector) => {
                 expect(injector.get(token)).toEqual(tokenValue);
                 async.done();
//.........这里部分代码省略.........
开发者ID:AngularLovers,项目名称:angular,代码行数:101,代码来源:regression_integration_spec.ts

示例4: describe

  describe('navigation', () => {
    beforeEachProviders(() => [
      provide(RouterUrlSerializer, {useClass: DefaultRouterUrlSerializer}),
      RouterOutletMap,
      provide(Location, {useClass: SpyLocation}),
      provide(RouteSegment, {useFactory: (r) => r.routeTree.root, deps: [Router]}),
      provide(Router,
              {
                useFactory: (resolver, urlParser, outletMap, location) => new Router(
                                "RootComponent", RootCmp, resolver, urlParser, outletMap, location),
                deps: [ComponentResolver, RouterUrlSerializer, RouterOutletMap, Location]
              })
    ]);

    it('should update location when navigating',
       fakeAsync(inject([Router, TestComponentBuilder, Location], (router, tcb, location) => {
         let fixture = tcb.createFakeAsync(RootCmp);

         router.navigateByUrl('/team/22/user/victor');
         advance(fixture);
         expect(location.path()).toEqual('/team/22/user/victor');

         router.navigateByUrl('/team/33/simple');
         advance(fixture);

         expect(location.path()).toEqual('/team/33/simple');
       })));

    it('should navigate when locations changes',
       fakeAsync(inject([Router, TestComponentBuilder, Location], (router, tcb, location) => {
         let fixture = tcb.createFakeAsync(RootCmp);

         router.navigateByUrl('/team/22/user/victor');
         advance(fixture);

         location.simulateHashChange("/team/22/user/fedor");
         advance(fixture);

         expect(fixture.debugElement.nativeElement).toHaveText('team 22 { hello fedor, aux:  }');
       })));

    it('should support nested routes',
       fakeAsync(inject([Router, TestComponentBuilder], (router, tcb) => {
         let fixture = tcb.createFakeAsync(RootCmp);

         router.navigateByUrl('/team/22/user/victor');
         advance(fixture);

         expect(fixture.debugElement.nativeElement).toHaveText('team 22 { hello victor, aux:  }');
       })));

    it('should support aux routes',
       fakeAsync(inject([Router, TestComponentBuilder], (router, tcb) => {
         let fixture = tcb.createFakeAsync(RootCmp);

         router.navigateByUrl('/team/22/user/victor(/simple)');
         advance(fixture);

         expect(fixture.debugElement.nativeElement)
             .toHaveText('team 22 { hello victor, aux: simple }');
       })));

    it('should deactivate outlets',
       fakeAsync(inject([Router, TestComponentBuilder], (router, tcb) => {
         let fixture = tcb.createFakeAsync(RootCmp);

         router.navigateByUrl('/team/22/user/victor(/simple)');
         advance(fixture);

         router.navigateByUrl('/team/22/user/victor');
         advance(fixture);

         expect(fixture.debugElement.nativeElement).toHaveText('team 22 { hello victor, aux:  }');
       })));

    it('should deactivate nested outlets',
       fakeAsync(inject([Router, TestComponentBuilder], (router, tcb) => {
         let fixture = tcb.createFakeAsync(RootCmp);

         router.navigateByUrl('/team/22/user/victor(/simple)');
         advance(fixture);

         router.navigateByUrl('/');
         advance(fixture);

         expect(fixture.debugElement.nativeElement).toHaveText('');
       })));

    it('should update nested routes when url changes',
       fakeAsync(inject([Router, TestComponentBuilder], (router, tcb) => {
         let fixture = tcb.createFakeAsync(RootCmp);

         router.navigateByUrl('/team/22/user/victor');
         advance(fixture);
         let team1 = fixture.debugElement.children[1].componentInstance;

         router.navigateByUrl('/team/22/user/fedor');
         advance(fixture);
         let team2 = fixture.debugElement.children[1].componentInstance;

//.........这里部分代码省略.........
开发者ID:2blessed2bstressedbythedevilsmess,项目名称:angular,代码行数:101,代码来源:integration_spec.ts

示例5: describe

  describe('fake async', () => {
    it('should run synchronous code', () => {
      var ran = false;
      fakeAsync(() => { ran = true; })();

      expect(ran).toEqual(true);
    });

    it('should pass arguments to the wrapped function', () => {
      fakeAsync((foo: any /** TODO #9100 */, bar: any /** TODO #9100 */) => {
        expect(foo).toEqual('foo');
        expect(bar).toEqual('bar');
      })('foo', 'bar');
    });

    it('should work with inject()', fakeAsync(inject([Parser], (parser: any /** TODO #9100 */) => {
         expect(parser).toBeAnInstanceOf(Parser);
       })));

    it('should throw on nested calls', () => {
      expect(() => {
        fakeAsync(() => { fakeAsync((): any /** TODO #9100 */ => null)(); })();
      }).toThrowError('fakeAsync() calls can not be nested');
    });

    it('should flush microtasks before returning', () => {
      var thenRan = false;

      fakeAsync(() => { resolvedPromise.then(_ => { thenRan = true; }); })();

      expect(thenRan).toEqual(true);
    });


    it('should propagate the return value',
       () => { expect(fakeAsync(() => 'foo')()).toEqual('foo'); });

    describe('Promise', () => {
      it('should run asynchronous code', fakeAsync(() => {
           var thenRan = false;
           resolvedPromise.then((_) => { thenRan = true; });

           expect(thenRan).toEqual(false);

           flushMicrotasks();
           expect(thenRan).toEqual(true);
         }));

      it('should run chained thens', fakeAsync(() => {
           var log = new Log();

           resolvedPromise.then((_) => log.add(1)).then((_) => log.add(2));

           expect(log.result()).toEqual('');

           flushMicrotasks();
           expect(log.result()).toEqual('1; 2');
         }));

      it('should run Promise created in Promise', fakeAsync(() => {
           var log = new Log();

           resolvedPromise.then((_) => {
             log.add(1);
             resolvedPromise.then((_) => log.add(2));
           });

           expect(log.result()).toEqual('');

           flushMicrotasks();
           expect(log.result()).toEqual('1; 2');
         }));

      it('should complain if the test throws an exception during async calls', () => {
        expect(() => {
          fakeAsync(() => {
            resolvedPromise.then((_) => { throw new BaseException('async'); });
            flushMicrotasks();
          })();
        }).toThrowError('Uncaught (in promise): async');
      });

      it('should complain if a test throws an exception', () => {
        expect(() => {
          fakeAsync(() => { throw new BaseException('sync'); })();
        }).toThrowError('sync');
      });

    });

    describe('timers', () => {
      it('should run queued zero duration timer on zero tick', fakeAsync(() => {
           var ran = false;
           setTimeout(() => { ran = true; }, 0);

           expect(ran).toEqual(false);

           tick();
           expect(ran).toEqual(true);
         }));
//.........这里部分代码省略.........
开发者ID:JamieMoon,项目名称:angular,代码行数:101,代码来源:fake_async_spec.ts

示例6: describe

    describe('readPerfLog (common)', () => {

      it('should execute a dummy script before reading them',
         inject([AsyncTestCompleter], (async) => {
           // TODO(tbosch): This seems to be a bug in ChromeDriver:
           // Sometimes it does not report the newest events of the performance log
           // to the WebDriver client unless a script is executed...
           createExtension([]).readPerfLog().then((_) => {
             expect(log).toEqual([['executeScript', '1+1'], ['logs', 'performance']]);
             async.done();
           });
         }));

      ['Rasterize', 'CompositeLayers'].forEach((recordType) => {
        it(`should report ${recordType} as "render"`, inject([AsyncTestCompleter], (async) => {
             createExtension(
                 [
                   chromeTimelineEvents.start(recordType, 1234),
                   chromeTimelineEvents.end(recordType, 2345)
                 ],
                 CHROME45_USER_AGENT)
                 .readPerfLog()
                 .then((events) => {
                   expect(events).toEqual([
                     normEvents.start('render', 1.234),
                     normEvents.end('render', 2.345),
                   ]);
                   async.done();
                 });
           }));
      });

      describe('frame metrics', () => {
        it('should report ImplThreadRenderingStats as frame event',
           inject([AsyncTestCompleter], (async) => {
             createExtension([benchmarkEvents.instant(
                                 'BenchmarkInstrumentation::ImplThreadRenderingStats', 1100,
                                 {'data': {'frame_count': 1}})])
                 .readPerfLog()
                 .then((events) => {
                   expect(events).toEqual([
                     normEvents.create('i', 'frame', 1.1),
                   ]);
                   async.done();
                 });
           }));

        it('should not report ImplThreadRenderingStats with zero frames',
           inject([AsyncTestCompleter], (async) => {
             createExtension([benchmarkEvents.instant(
                                 'BenchmarkInstrumentation::ImplThreadRenderingStats', 1100,
                                 {'data': {'frame_count': 0}})])
                 .readPerfLog()
                 .then((events) => {
                   expect(events).toEqual([]);
                   async.done();
                 });
           }));

        it('should throw when ImplThreadRenderingStats contains more than one frame',
           inject([AsyncTestCompleter], (async) => {

             createExtension([benchmarkEvents.instant(
                                 'BenchmarkInstrumentation::ImplThreadRenderingStats', 1100,
                                 {'data': {'frame_count': 2}})])
                 .readPerfLog()
                 .catch((err): any => {
                   expect(() => {
                     throw err;
                   }).toThrowError('multi-frame render stats not supported');
                   async.done();
                 });
           }));

      });

      it('should report begin timestamps', inject([AsyncTestCompleter], (async) => {
           createExtension([blinkEvents.create('S', 'someName', 1000)])
               .readPerfLog()
               .then((events) => {
                 expect(events).toEqual([normEvents.markStart('someName', 1.0)]);
                 async.done();
               });
         }));

      it('should report end timestamps', inject([AsyncTestCompleter], (async) => {
           createExtension([blinkEvents.create('F', 'someName', 1000)])
               .readPerfLog()
               .then((events) => {
                 expect(events).toEqual([normEvents.markEnd('someName', 1.0)]);
                 async.done();
               });
         }));

      it('should throw an error on buffer overflow', inject([AsyncTestCompleter], (async) => {

           createExtension(
               [
                 chromeTimelineEvents.start('FunctionCall', 1234),
               ],
//.........这里部分代码省略.........
开发者ID:Jake-Church,项目名称:angular,代码行数:101,代码来源:chrome_driver_extension_spec.ts

示例7: describe

  describe('navigation', () => {

    var tcb: TestComponentBuilder;
    var fixture: ComponentFixture<any>;
    var rtr: any /** TODO #9100 */;

    beforeEachProviders(() => TEST_ROUTER_PROVIDERS);

    beforeEach(inject([TestComponentBuilder, Router], (tcBuilder: any /** TODO #9100 */, router: any /** TODO #9100 */) => {
      tcb = tcBuilder;
      rtr = router;
      childCmpInstanceCount = 0;
      cmpInstanceCount = 0;
    }));

    it('should work in a simple case', inject([AsyncTestCompleter], (async: any /** TODO #9100 */) => {
         compile(tcb)
             .then((rtc) => {fixture = rtc})
             .then((_) => rtr.config([new Route({path: '/test', component: HelloCmp})]))
             .then((_) => rtr.navigateByUrl('/test'))
             .then((_) => {
               fixture.detectChanges();
               expect(fixture.debugElement.nativeElement).toHaveText('hello');
               async.done();
             });
       }));


    it('should navigate between components with different parameters',
       inject([AsyncTestCompleter], (async: any /** TODO #9100 */) => {
         compile(tcb)
             .then((rtc) => {fixture = rtc})
             .then((_) => rtr.config([new Route({path: '/user/:name', component: UserCmp})]))
             .then((_) => rtr.navigateByUrl('/user/brian'))
             .then((_) => {
               fixture.detectChanges();
               expect(fixture.debugElement.nativeElement).toHaveText('hello brian');
             })
             .then((_) => rtr.navigateByUrl('/user/igor'))
             .then((_) => {
               fixture.detectChanges();
               expect(fixture.debugElement.nativeElement).toHaveText('hello igor');
               async.done();
             });
       }));

    it('should navigate to child routes', inject([AsyncTestCompleter], (async: any /** TODO #9100 */) => {
         compile(tcb, 'outer { <router-outlet></router-outlet> }')
             .then((rtc) => {fixture = rtc})
             .then((_) => rtr.config([new Route({path: '/a/...', component: ParentCmp})]))
             .then((_) => rtr.navigateByUrl('/a/b'))
             .then((_) => {
               fixture.detectChanges();
               expect(fixture.debugElement.nativeElement).toHaveText('outer { inner { hello } }');
               async.done();
             });
       }));

    it('should navigate to child routes that capture an empty path',
       inject([AsyncTestCompleter], (async: any /** TODO #9100 */) => {

         compile(tcb, 'outer { <router-outlet></router-outlet> }')
             .then((rtc) => {fixture = rtc})
             .then((_) => rtr.config([new Route({path: '/a/...', component: ParentCmp})]))
             .then((_) => rtr.navigateByUrl('/a'))
             .then((_) => {
               fixture.detectChanges();
               expect(fixture.debugElement.nativeElement).toHaveText('outer { inner { hello } }');
               async.done();
             });
       }));

    it('should navigate to child routes when the root component has an empty path',
       inject([AsyncTestCompleter, Location], (async: any /** TODO #9100 */, location: any /** TODO #9100 */) => {
         compile(tcb, 'outer { <router-outlet></router-outlet> }')
             .then((rtc) => {fixture = rtc})
             .then((_) => rtr.config([new Route({path: '/...', component: ParentCmp})]))
             .then((_) => rtr.navigateByUrl('/b'))
             .then((_) => {
               fixture.detectChanges();
               expect(fixture.debugElement.nativeElement).toHaveText('outer { inner { hello } }');
               expect(location.urlChanges).toEqual(['/b']);
               async.done();
             });
       }));

    it('should navigate to child routes of async routes', inject([AsyncTestCompleter], (async: any /** TODO #9100 */) => {
         compile(tcb, 'outer { <router-outlet></router-outlet> }')
             .then((rtc) => {fixture = rtc})
             .then((_) => rtr.config([new AsyncRoute({path: '/a/...', loader: parentLoader})]))
             .then((_) => rtr.navigateByUrl('/a/b'))
             .then((_) => {
               fixture.detectChanges();
               expect(fixture.debugElement.nativeElement).toHaveText('outer { inner { hello } }');
               async.done();
             });
       }));


    it('should replace state when normalized paths are equal',
//.........这里部分代码省略.........
开发者ID:aftab10662,项目名称:angular,代码行数:101,代码来源:navigation_spec.ts

示例8: describe

    describe('loadTemplate', () => {
      describe('inline template', () => {
        it('should store the template',
           inject([AsyncTestCompleter, DirectiveNormalizer],
                  (async: AsyncTestCompleter, normalizer: DirectiveNormalizer) => {
                    normalizer.normalizeTemplate(dirType, new CompileTemplateMetadata({
                                                   encapsulation: null,
                                                   template: 'a',
                                                   templateUrl: null,
                                                   styles: [],
                                                   styleUrls: ['test.css']
                                                 }))
                        .then((template: CompileTemplateMetadata) => {
                          expect(template.template).toEqual('a');
                          expect(template.templateUrl).toEqual('package:some/module/a.js');
                          async.done();
                        });
                  }));

        it('should resolve styles on the annotation against the moduleUrl',
           inject([AsyncTestCompleter, DirectiveNormalizer],
                  (async: AsyncTestCompleter, normalizer: DirectiveNormalizer) => {
                    normalizer.normalizeTemplate(dirType, new CompileTemplateMetadata({
                                                   encapsulation: null,
                                                   template: '',
                                                   templateUrl: null,
                                                   styles: [],
                                                   styleUrls: ['test.css']
                                                 }))
                        .then((template: CompileTemplateMetadata) => {
                          expect(template.styleUrls).toEqual(['package:some/module/test.css']);
                          async.done();
                        });
                  }));

        it('should resolve styles in the template against the moduleUrl',
           inject([AsyncTestCompleter, DirectiveNormalizer],
                  (async: AsyncTestCompleter, normalizer: DirectiveNormalizer) => {
                    normalizer.normalizeTemplate(dirType, new CompileTemplateMetadata({
                                                   encapsulation: null,
                                                   template: '<style>@import test.css</style>',
                                                   templateUrl: null,
                                                   styles: [],
                                                   styleUrls: []
                                                 }))
                        .then((template: CompileTemplateMetadata) => {
                          expect(template.styleUrls).toEqual(['package:some/module/test.css']);
                          async.done();
                        });
                  }));

        it('should use ViewEncapsulation.Emulated by default',
           inject([AsyncTestCompleter, DirectiveNormalizer],
                  (async: AsyncTestCompleter, normalizer: DirectiveNormalizer) => {
                    normalizer.normalizeTemplate(dirType, new CompileTemplateMetadata({
                                                   encapsulation: null,
                                                   template: '',
                                                   templateUrl: null,
                                                   styles: [],
                                                   styleUrls: ['test.css']
                                                 }))
                        .then((template: CompileTemplateMetadata) => {
                          expect(template.encapsulation).toEqual(ViewEncapsulation.Emulated);
                          async.done();
                        });
                  }));

        it('should use default encapsulation provided by CompilerConfig',
           inject([AsyncTestCompleter, CompilerConfig , DirectiveNormalizer],
                  (async: AsyncTestCompleter, config: CompilerConfig, normalizer: DirectiveNormalizer) => {
                    config.defaultEncapsulation = ViewEncapsulation.None;
                    normalizer.normalizeTemplate(dirType, new CompileTemplateMetadata({
                                                   encapsulation: null,
                                                   template: '',
                                                   templateUrl: null,
                                                   styles: [],
                                                   styleUrls: ['test.css']
                                                 }))
                        .then((template: CompileTemplateMetadata) => {
                          expect(template.encapsulation).toEqual(ViewEncapsulation.None);
                          async.done();
                        });
                  }));
      });

      describe('templateUrl', () => {

        it('should load a template from a url that is resolved against moduleUrl',
           inject([AsyncTestCompleter, DirectiveNormalizer, XHR],
                  (async: AsyncTestCompleter, normalizer: DirectiveNormalizer, xhr: MockXHR) => {
                    xhr.expect('package:some/module/sometplurl.html', 'a');
                    normalizer.normalizeTemplate(dirType, new CompileTemplateMetadata({
                                                   encapsulation: null,
                                                   template: null,
                                                   templateUrl: 'sometplurl.html',
                                                   styles: [],
                                                   styleUrls: ['test.css']
                                                 }))
                        .then((template: CompileTemplateMetadata) => {
                          expect(template.template).toEqual('a');
//.........这里部分代码省略.........
开发者ID:haroldoramirez,项目名称:angular,代码行数:101,代码来源:directive_normalizer_spec.ts

示例9: asyncRoutesWithoutChildrenWithoutParams

function asyncRoutesWithoutChildrenWithoutParams() {
  var fixture: any /** TODO #9100 */;
  var tcb: any /** TODO #9100 */;
  var rtr: any /** TODO #9100 */;

  beforeEachProviders(() => TEST_ROUTER_PROVIDERS);

  beforeEach(inject([TestComponentBuilder, Router], (tcBuilder: any /** TODO #9100 */, router: any /** TODO #9100 */) => {
    tcb = tcBuilder;
    rtr = router;
  }));

  it('should navigate by URL', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
       compile(tcb)
           .then((rtc) => {fixture = rtc})
           .then((_) => rtr.config(
                     [new AsyncRoute({path: '/test', loader: helloCmpLoader, name: 'Hello'})]))
           .then((_) => rtr.navigateByUrl('/test'))
           .then((_) => {
             fixture.detectChanges();
             expect(fixture.debugElement.nativeElement).toHaveText('hello');
             async.done();
           });
     }));

  it('should navigate by link DSL', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
       compile(tcb)
           .then((rtc) => {fixture = rtc})
           .then((_) => rtr.config(
                     [new AsyncRoute({path: '/test', loader: helloCmpLoader, name: 'Hello'})]))
           .then((_) => rtr.navigate(['/Hello']))
           .then((_) => {
             fixture.detectChanges();
             expect(fixture.debugElement.nativeElement).toHaveText('hello');
             async.done();
           });
     }));

  it('should generate a link URL', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
       compile(tcb, `<a [routerLink]="['Hello']">go to hello</a> | <router-outlet></router-outlet>`)
           .then((rtc) => {fixture = rtc})
           .then((_) => rtr.config(
                     [new AsyncRoute({path: '/test', loader: helloCmpLoader, name: 'Hello'})]))
           .then((_) => {
             fixture.detectChanges();
             expect(getHref(getLinkElement(fixture))).toEqual('/test');
             async.done();
           });
     }));

  it('should navigate from a link click',
     inject([AsyncTestCompleter, Location], (async: AsyncTestCompleter, location: any /** TODO #9100 */) => {
       compile(tcb, `<a [routerLink]="['Hello']">go to hello</a> | <router-outlet></router-outlet>`)
           .then((rtc) => {fixture = rtc})
           .then((_) => rtr.config(
                     [new AsyncRoute({path: '/test', loader: helloCmpLoader, name: 'Hello'})]))
           .then((_) => {
             fixture.detectChanges();
             expect(fixture.debugElement.nativeElement).toHaveText('go to hello | ');

             rtr.subscribe((_: any /** TODO #9100 */) => {
               fixture.detectChanges();
               expect(fixture.debugElement.nativeElement).toHaveText('go to hello | hello');
               expect(location.urlChanges).toEqual(['/test']);
               async.done();
             });

             clickOnElement(getLinkElement(fixture));
           });
     }));
}
开发者ID:haroldoramirez,项目名称:angular,代码行数:71,代码来源:async_route_spec_impl.ts


注:本文中的@angular/core/testing/testing_internal.inject函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。