Example #1
0
 appRef.registerBootstrapListener(() => { injector.get(Router).initialNavigation(); });
 constructor(injector: Injector) {
   this.defaultCounterId = injector.get<string>(DEFAULT_COUNTER_ID);
   this.counterConfigs = injector.get<YandexCounterConfig[]>(YANDEX_COUNTERS_CONFIGS);
   this.positionToId = this.counterConfigs.map(config => config.id);
 }
Example #3
0
 constructor(service: Service, injector: Injector) {
   this.instance1 = service.instance;
   this.instance2 = injector.get(Service).instance;
 }
describe('ResourceService', () => {

  let injector: Injector;
  let resourceService: ResourceService;
  let httpMock: HttpTestingController;

  beforeEach(() => {
    injector = TestBed.configureTestingModule({
      imports: [HttpClientTestingModule],
      providers: [
        ResourceService
      ]
    });

    resourceService = injector.get(ResourceService);
    httpMock = injector.get(HttpTestingController);
  });

  afterEach(() => httpMock.verify());

  it('should make a single connection to the server', () => {
    const req = httpMock.expectOne({});
    expect(req.request.url).toBe('generated/resources.json');
  });

  describe('#categories', () => {

    let categories: Category[];
    let testData: any;

    beforeEach(() => {
      testData = getTestResources();
      httpMock.expectOne({}).flush(testData);
      resourceService.categories.subscribe(results => categories = results);
    });

    it('categories observable should complete', () => {
      let completed = false;
      resourceService.categories.subscribe(null, null, () => completed = true);
      expect(true).toBe(true, 'observable completed');
    });

    it('should reshape contributors.json to sorted category array', () => {
      const actualIds = categories.map(c => c.id).join(',');
      expect(actualIds).toBe('cat-1,cat-3');
    });

    it('should convert ids to canonical form', () => {
      // canonical form is lowercase with dashes for spaces
      const cat = categories[1];
      const sub = cat.subCategories[0];
      const res = sub.resources[0];

      expect(cat.id).toBe('cat-3', 'category id');
      expect(sub.id).toBe('cat3-subcat2', 'subcat id');
      expect(res.id).toBe('cat3-subcat2-res1', 'resources id');
    });

    it('resource knows its category and sub-category titles', () => {
      const cat = categories[1];
      const sub = cat.subCategories[0];
      const res = sub.resources[0];
      expect(res.category).toBe(cat.title, 'category title');
      expect(res.subCategory).toBe(sub.title, 'subcategory title');
    });

    it('should have expected SubCategories of "Cat 3"', () => {
      const actualIds = categories[1].subCategories.map(s => s.id).join(',');
      expect(actualIds).toBe('cat3-subcat2,cat3-subcat1');
    });

    it('should have expected sorted resources of "Cat 1:SubCat1"', () => {
      const actualIds = categories[0].subCategories[0].resources.map(r => r.id).join(',');
      expect(actualIds).toBe('a-a-a,s-s-s,z-z-z');
    });
  });

  it('should do WHAT(?) if the request fails');
});
Example #5
0
 it('merges imports and exports', () => { expect(injector.get(AOT_TOKEN)).toEqual('exports'); });
Example #6
0
 function(injector: Injector) {
   runBlockTriggered = true;
   expect(injector.get($INJECTOR)).toBeDefined();
 }
 beforeEach(inject([ Injector ], (injector: Injector) => {
     audioContext = injector.get<IAudioContext>(AudioContext);
     isSupported = injector.get<() => Promise<boolean>>(audioContextModuleIsSupported);
 }));
 constructor(protected injector: Injector) {
   this.config = this.injector.get(AppConfig).getConfiguration();
 }
Example #9
0
 beforeEach(() => {
   locationService = injector.get(LocationService) as any as MockLocationService;
   navService.currentNodes.subscribe(selected => currentNodes = selected);
   httpMock.expectOne({}).flush(navJson);
 });
Example #10
0
  return () => {
    let zone = injector.get(NgZone);

    zone.runGuarded(() => injector.get(MessageBasedPlatformLocation).start());
  };
Example #11
0
 zone.runGuarded(() => injector.get(MessageBasedPlatformLocation).start());
    private static getUserConfiguration(injector: Injector, callback: () => void) {
        let httpClient: HttpClient = injector.get(HttpClient);

        let requestHeaders = {
            Authorization: 'Bearer ' + Abp.auth.getToken()
        };
        if(Abp.multiTenancy.getTenantIdCookie()){
            requestHeaders['Abp.TenantId'] = Abp.multiTenancy.getTenantIdCookie().toString();
        }
        if(Abp.utils.getCookieValue("Abp.Localization.CultureName")){
            requestHeaders['.AspNetCore.Culture'] = Abp.utils.getCookieValue("Abp.Localization.CultureName");
        }

        httpClient.get<any>(AppConsts.remoteServiceBaseUrl + '/AbpUserConfiguration/GetAll', {
            headers: requestHeaders
        }).subscribe(res=>{
            let result = res.result;
            // $.extend(true, Abp, result);
            console.log('AbpUserConfiguration: %o', result);

            Abp.multiTenancy.setGlobal(result.multiTenancy);
            Abp.session.setGlobal(result.session);
            Abp.localization.setGlobal(result.localization);
            Abp.features.setGlobal(result.features);
            Abp.auth.setGlobal(result.auth);
            Abp.nav.setGlobal(result.nav);
            Abp.setting.setGlobal(result.setting);

            Abp.clock.setGloabl(result.clock);
            Abp.timing.setGloabl(result.timing);

            Abp.clock.provider = this.getCurrentClockProvider(result.clock.provider);

            moment.locale(Abp.localization.currentLanguage.name);

            if (Abp.clock.provider.supportsMultipleTimezone) {
                moment.tz.setDefault(Abp.timing.timeZoneInfo.iana.timeZoneId);
            }

            callback();
        });

        // return abp.ajax({
        //     url: AppConsts.remoteServiceBaseUrl + '/AbpUserConfiguration/GetAll',
        //     method: 'GET',
        //     headers: {
        //         Authorization: 'Bearer ' + abp.auth.getToken(),
        //         '.AspNetCore.Culture': abp.utils.getCookieValue("Abp.Localization.CultureName"),
        //         'Abp.TenantId': abp.multiTenancy.getTenantIdCookie()
        //     }
        // }).done(result => {
        //     $.extend(true, abp, result);

        //     abp.clock.provider = this.getCurrentClockProvider(result.clock.provider);

        //     moment.locale(abp.localization.currentLanguage.name);

        //     if (abp.clock.provider.supportsMultipleTimezone) {
        //         moment.tz.setDefault(abp.timing.timeZoneInfo.iana.timeZoneId);
        //     }

        //     callback();
        // });
    }
 private get errorModalService(): ErrorModalService {
   return this.injector.get(ErrorModalService);
 }
Example #14
0
 handleError(err: any): void {
   const rollbar = this.injector.get(RollbarService);
   rollbar.error(err.originalError || err);
 }
 ]).then((injector: Injector) => {
   expect(injector.get(token)).toEqual(tokenValue);
   async.done();
 });
Example #16
0
describe('NavigationService', () => {

  let injector: Injector;
  let navService: NavigationService;
  let httpMock: HttpTestingController;

  beforeEach(() => {
    injector = TestBed.configureTestingModule({
      imports: [HttpClientTestingModule],
      providers: [
        NavigationService,
        { provide: LocationService, useFactory: () => new MockLocationService('a') }
      ]
    });

    navService = injector.get(NavigationService);
    httpMock = injector.get(HttpTestingController);
  });

  afterEach(() => httpMock.verify());

  describe('navigationViews', () => {

    it('should make a single connection to the server', () => {
      const req = httpMock.expectOne({});
      expect(req.request.url).toBe('generated/navigation.json');
    });

    it('should expose the server response', () => {
      const viewsEvents: NavigationViews[] = [];
      navService.navigationViews.subscribe(views => viewsEvents.push(views));

      expect(viewsEvents).toEqual([]);
      httpMock.expectOne({}).flush({ TopBar: [ { url: 'a' }] });
      expect(viewsEvents).toEqual([{ TopBar: [ { url: 'a' }] }]);
    });

    it('navigationViews observable should complete', () => {
      let completed = false;
      navService.navigationViews.subscribe(undefined, undefined, () => completed = true);

      // Stop `$httpMock.verify()` from complaining.
      httpMock.expectOne({}).flush({});

      expect(completed).toBe(true, 'observable completed');
    });

    it('should return the same object to all subscribers', () => {
      let views1: NavigationViews|undefined;
      navService.navigationViews.subscribe(views => views1 = views);

      let views2: NavigationViews|undefined;
      navService.navigationViews.subscribe(views => views2 = views);

      httpMock.expectOne({}).flush({ TopBar: [{ url: 'a' }] });

      let views3: NavigationViews|undefined;
      navService.navigationViews.subscribe(views => views3 = views);

      expect(views2).toBe(views1);
      expect(views3).toBe(views1);

      // Verfy that subsequent subscriptions did not trigger another request.
      httpMock.expectNone({});
    });

    it('should do WHAT(?) if the request fails');
  });

  describe('node.tooltip', () => {
    let view: NavigationNode[];

    const sideNav: NavigationNode[] = [
      { title: 'a', tooltip: 'a tip' },
      { title: 'b' },
      { title: 'c!'},
      { url: 'foo' }
    ];

    beforeEach(() => {
      navService.navigationViews.subscribe(views => view = views['sideNav']);
      httpMock.expectOne({}).flush({sideNav});
    });

    it('should have the supplied tooltip', () => {
      expect(view[0].tooltip).toEqual('a tip');
    });

    it('should create a tooltip from title + period', () => {
      expect(view[1].tooltip).toEqual('b.');
    });

    it('should create a tooltip from title, keeping its trailing punctuation', () => {
      expect(view[2].tooltip).toEqual('c!');
    });

    it('should not create a tooltip if there is no title', () => {
      expect(view[3].tooltip).toBeUndefined();
    });
  });

  describe('currentNode', () => {
    let currentNodes: CurrentNodes;
    let locationService: MockLocationService;

    const topBarNodes: NavigationNode[] = [
      { url: 'features', title: 'Features', tooltip: 'tip' }
    ];
    const sideNavNodes: NavigationNode[] = [
        { title: 'a', tooltip: 'tip', children: [
          { url: 'b', title: 'b', tooltip: 'tip', children: [
            { url: 'c', title: 'c', tooltip: 'tip' },
            { url: 'd', title: 'd', tooltip: 'tip' }
          ] },
          { url: 'e', title: 'e', tooltip: 'tip' }
        ] },
        { url: 'f', title: 'f', tooltip: 'tip' }
      ];

    const navJson = {
      TopBar: topBarNodes,
      SideNav: sideNavNodes,
      __versionInfo: {}
    };

    beforeEach(() => {
      locationService = injector.get(LocationService) as any as MockLocationService;
      navService.currentNodes.subscribe(selected => currentNodes = selected);
      httpMock.expectOne({}).flush(navJson);
    });

    it('should list the side navigation node that matches the current location, and all its ancestors', () => {
      locationService.go('b');
      expect(currentNodes).toEqual({
        SideNav: {
          url: 'b',
          view: 'SideNav',
          nodes: [
            sideNavNodes[0].children![0],
            sideNavNodes[0]
          ]
        }
      });

      locationService.go('d');
      expect(currentNodes).toEqual({
        SideNav: {
          url: 'd',
          view: 'SideNav',
          nodes: [
            sideNavNodes[0].children![0].children![1],
            sideNavNodes[0].children![0],
            sideNavNodes[0]
          ]
        }
      });

      locationService.go('f');
      expect(currentNodes).toEqual({
        SideNav: {
          url: 'f',
          view: 'SideNav',
          nodes: [ sideNavNodes[1] ]
        }
      });
    });

    it('should be a TopBar selected node if the current location is a top menu node', () => {
      locationService.go('features');
      expect(currentNodes).toEqual({
        TopBar: {
          url: 'features',
          view: 'TopBar',
          nodes: [ topBarNodes[0] ]
        }
      });
    });

    it('should be a plain object if no navigation node matches the current location', () => {
      locationService.go('g?search=moo#anchor-1');
      expect(currentNodes).toEqual({
        '': {
          url: 'g',
          view: '',
          nodes: []
        }
      });
    });

    it('should ignore trailing slashes, hashes, and search params on URLs in the navmap', () => {
      const cnode: CurrentNodes = {
        SideNav: {
          url: 'c',
          view: 'SideNav',
          nodes: [
            sideNavNodes[0].children![0].children![0],
            sideNavNodes[0].children![0],
            sideNavNodes[0]
          ]
        }
      };

      locationService.go('c');
      expect(currentNodes).toEqual(cnode, 'location: c');

      locationService.go('c#foo');
      expect(currentNodes).toEqual(cnode, 'location: c#foo');

      locationService.go('c?foo=1');
      expect(currentNodes).toEqual(cnode, 'location: c?foo=1');

      locationService.go('c#foo?bar=1&baz=2');
      expect(currentNodes).toEqual(cnode, 'location: c#foo?bar=1&baz=2');
    });
  });

  describe('versionInfo', () => {
    const expectedVersionInfo = { raw: '4.0.0' } as VersionInfo;
    let versionInfo: VersionInfo;

    beforeEach(() => {
      navService.versionInfo.subscribe(info => versionInfo = info);
      httpMock.expectOne({}).flush({
        __versionInfo: expectedVersionInfo
      });
    });

    it('should extract the version info', () => {
      expect(versionInfo).toEqual(expectedVersionInfo);
    });
  });

  describe('docVersions', () => {
    let actualDocVersions: NavigationNode[];
    let docVersions: NavigationNode[];
    let expectedDocVersions: NavigationNode[];

    beforeEach(() => {
      actualDocVersions = [];
      docVersions = [
        { title: 'v4.0.0' },
        { title: 'v2', url: 'https://v2.angular.io' }
      ];

      expectedDocVersions = docVersions.map(v => (
        {...v, ...{ tooltip: v.title + '.'}})
      );

      navService.navigationViews.subscribe(views => actualDocVersions = views['docVersions']);
    });

    it('should extract the docVersions', () => {
      httpMock.expectOne({}).flush({ docVersions });
      expect(actualDocVersions).toEqual(expectedDocVersions);
    });
  });
});
 public getDocument():any {
   return this.injector.get(DOCUMENT);
 }
Example #18
0
 ngOnInit() {
     this.router = this.injector.get(Router);
 }
describe('ScrollSpyService', () => {
  let injector: Injector;
  let scrollSpyService: ScrollSpyService;

  beforeEach(() => {
    injector = ReflectiveInjector.resolveAndCreate([
      { provide: DOCUMENT, useValue: { body: {} } },
      { provide: ScrollService, useValue: { topOffset: 50 } },
      ScrollSpyService
    ]);

    scrollSpyService = injector.get(ScrollSpyService);
  });


  describe('#spyOn()', () => {
    let getSpiedElemGroups: () => ScrollSpiedElementGroup[];

    beforeEach(() => {
      getSpiedElemGroups = () => (scrollSpyService as any).spiedElementGroups;
    });


    it('should create a `ScrollSpiedElementGroup` when called', () => {
      expect(getSpiedElemGroups().length).toBe(0);

      scrollSpyService.spyOn([]);
      expect(getSpiedElemGroups().length).toBe(1);
    });

    it('should initialize the newly created `ScrollSpiedElementGroup`', () => {
      const calibrateSpy = spyOn(ScrollSpiedElementGroup.prototype, 'calibrate');
      const onScrollSpy = spyOn(ScrollSpiedElementGroup.prototype, 'onScroll');

      scrollSpyService.spyOn([]);
      expect(calibrateSpy).toHaveBeenCalledTimes(1);
      expect(onScrollSpy).toHaveBeenCalledTimes(1);

      scrollSpyService.spyOn([]);
      expect(calibrateSpy).toHaveBeenCalledTimes(2);
      expect(onScrollSpy).toHaveBeenCalledTimes(2);
    });

    it('should call `onResize()` if it is the first `ScrollSpiedElementGroup`', () => {
      const actions: string[] = [];

      const onResizeSpy = spyOn(ScrollSpyService.prototype as any, 'onResize')
                          .and.callFake(() => actions.push('onResize'));
      const calibrateSpy = spyOn(ScrollSpiedElementGroup.prototype, 'calibrate')
                           .and.callFake(() => actions.push('calibrate'));

      expect(onResizeSpy).not.toHaveBeenCalled();

      scrollSpyService.spyOn([]);
      expect(actions).toEqual(['onResize', 'calibrate']);

      scrollSpyService.spyOn([]);
      expect(actions).toEqual(['onResize', 'calibrate', 'calibrate']);
    });

    it('should forward `ScrollSpiedElementGroup#activeScrollItem` as `active`', () => {
      const activeIndices1: (number | null)[] = [];
      const activeIndices2: (number | null)[] = [];

      const info1 = scrollSpyService.spyOn([]);
      const info2 = scrollSpyService.spyOn([]);
      const spiedElemGroups = getSpiedElemGroups();

      info1.active.subscribe(item => activeIndices1.push(item && item.index));
      info2.active.subscribe(item => activeIndices2.push(item && item.index));
      activeIndices1.length = 0;
      activeIndices2.length = 0;

      spiedElemGroups[0].activeScrollItem.next({index: 1} as ScrollItem);
      spiedElemGroups[0].activeScrollItem.next({index: 2} as ScrollItem);
      spiedElemGroups[1].activeScrollItem.next({index: 3} as ScrollItem);
      spiedElemGroups[0].activeScrollItem.next(null);
      spiedElemGroups[1].activeScrollItem.next({index: 4} as ScrollItem);
      spiedElemGroups[1].activeScrollItem.next(null);
      spiedElemGroups[0].activeScrollItem.next({index: 5} as ScrollItem);
      spiedElemGroups[1].activeScrollItem.next({index: 6} as ScrollItem);

      expect(activeIndices1).toEqual([1, 2, null, 5]);
      expect(activeIndices2).toEqual([3, 4, null, 6]);
    });

    it('should remember and emit the last active item to new subscribers', () => {
      const items = [{index: 1}, {index: 2}, {index: 3}] as ScrollItem[];
      let lastActiveItem: ScrollItem | null;

      const info = scrollSpyService.spyOn([]);
      const spiedElemGroup = getSpiedElemGroups()[0];

      spiedElemGroup.activeScrollItem.next(items[0]);
      spiedElemGroup.activeScrollItem.next(items[1]);
      spiedElemGroup.activeScrollItem.next(items[2]);
      spiedElemGroup.activeScrollItem.next(null);
      spiedElemGroup.activeScrollItem.next(items[1]);
      info.active.subscribe(item => lastActiveItem = item);

      expect(lastActiveItem).toBe(items[1]);

      spiedElemGroup.activeScrollItem.next(null);
      info.active.subscribe(item => lastActiveItem = item);

      expect(lastActiveItem).toBeNull();
    });

    it('should only emit distinct values on `active`', () => {
      const items = [{index: 1}, {index: 2}] as ScrollItem[];
      const activeIndices: (number | null)[] = [];

      const info = scrollSpyService.spyOn([]);
      const spiedElemGroup = getSpiedElemGroups()[0];

      info.active.subscribe(item => activeIndices.push(item && item.index));
      activeIndices.length = 0;

      spiedElemGroup.activeScrollItem.next(items[0]);
      spiedElemGroup.activeScrollItem.next(items[0]);
      spiedElemGroup.activeScrollItem.next(items[1]);
      spiedElemGroup.activeScrollItem.next(items[1]);
      spiedElemGroup.activeScrollItem.next(null);
      spiedElemGroup.activeScrollItem.next(null);
      spiedElemGroup.activeScrollItem.next(items[0]);
      spiedElemGroup.activeScrollItem.next(items[1]);
      spiedElemGroup.activeScrollItem.next(null);

      expect(activeIndices).toEqual([1, 2, null, 1, 2, null]);
    });

    it('should remove the corresponding `ScrollSpiedElementGroup` when calling `unspy()`', () => {
      const info1 = scrollSpyService.spyOn([]);
      const info2 = scrollSpyService.spyOn([]);
      const info3 = scrollSpyService.spyOn([]);
      const groups = getSpiedElemGroups().slice();

      expect(getSpiedElemGroups()).toEqual(groups);

      info2.unspy();
      expect(getSpiedElemGroups()).toEqual([groups[0], groups[2]]);

      info1.unspy();
      expect(getSpiedElemGroups()).toEqual([groups[2]]);

      info3.unspy();
      expect(getSpiedElemGroups()).toEqual([]);
    });
  });

  describe('window resize events', () => {
    const RESIZE_EVENT_DELAY = 300;
    let onResizeSpy: jasmine.Spy;

    beforeEach(() => {
      onResizeSpy = spyOn(ScrollSpyService.prototype as any, 'onResize');
    });


    it('should be subscribed to when the first group of elements is spied on', fakeAsync(() => {
      window.dispatchEvent(new Event('resize'));
      expect(onResizeSpy).not.toHaveBeenCalled();

      scrollSpyService.spyOn([]);
      onResizeSpy.calls.reset();

      window.dispatchEvent(new Event('resize'));
      expect(onResizeSpy).not.toHaveBeenCalled();

      tick(RESIZE_EVENT_DELAY);
      expect(onResizeSpy).toHaveBeenCalled();
    }));

    it('should be unsubscribed from when the last group of elements is removed', fakeAsync(() => {
      const info1 = scrollSpyService.spyOn([]);
      const info2 = scrollSpyService.spyOn([]);
      onResizeSpy.calls.reset();

      window.dispatchEvent(new Event('resize'));
      tick(RESIZE_EVENT_DELAY);
      expect(onResizeSpy).toHaveBeenCalled();

      info1.unspy();
      onResizeSpy.calls.reset();

      window.dispatchEvent(new Event('resize'));
      tick(RESIZE_EVENT_DELAY);
      expect(onResizeSpy).toHaveBeenCalled();

      info2.unspy();
      onResizeSpy.calls.reset();

      window.dispatchEvent(new Event('resize'));
      tick(RESIZE_EVENT_DELAY);
      expect(onResizeSpy).not.toHaveBeenCalled();
    }));

    it(`should only fire every ${RESIZE_EVENT_DELAY}ms`, fakeAsync(() => {
      scrollSpyService.spyOn([]);
      onResizeSpy.calls.reset();

      window.dispatchEvent(new Event('resize'));
      tick(RESIZE_EVENT_DELAY - 2);
      expect(onResizeSpy).not.toHaveBeenCalled();

      window.dispatchEvent(new Event('resize'));
      tick(1);
      expect(onResizeSpy).not.toHaveBeenCalled();

      window.dispatchEvent(new Event('resize'));
      tick(1);
      expect(onResizeSpy).toHaveBeenCalledTimes(1);

      onResizeSpy.calls.reset();
      tick(RESIZE_EVENT_DELAY / 2);

      window.dispatchEvent(new Event('resize'));
      tick(RESIZE_EVENT_DELAY - 2);
      expect(onResizeSpy).not.toHaveBeenCalled();

      window.dispatchEvent(new Event('resize'));
      tick(1);
      expect(onResizeSpy).not.toHaveBeenCalled();

      window.dispatchEvent(new Event('resize'));
      tick(1);
      expect(onResizeSpy).toHaveBeenCalledTimes(1);
    }));
  });

  describe('window scroll events', () => {
    const SCROLL_EVENT_DELAY = 10;
    let onScrollSpy: jasmine.Spy;

    beforeEach(() => {
      onScrollSpy = spyOn(ScrollSpyService.prototype as any, 'onScroll');
    });


    it('should be subscribed to when the first group of elements is spied on', fakeAsync(() => {
      window.dispatchEvent(new Event('scroll'));
      expect(onScrollSpy).not.toHaveBeenCalled();

      scrollSpyService.spyOn([]);

      window.dispatchEvent(new Event('scroll'));
      expect(onScrollSpy).not.toHaveBeenCalled();

      tick(SCROLL_EVENT_DELAY);
      expect(onScrollSpy).toHaveBeenCalled();
    }));

    it('should be unsubscribed from when the last group of elements is removed', fakeAsync(() => {
      const info1 = scrollSpyService.spyOn([]);
      const info2 = scrollSpyService.spyOn([]);

      window.dispatchEvent(new Event('scroll'));
      tick(SCROLL_EVENT_DELAY);
      expect(onScrollSpy).toHaveBeenCalled();

      info1.unspy();
      onScrollSpy.calls.reset();

      window.dispatchEvent(new Event('scroll'));
      tick(SCROLL_EVENT_DELAY);
      expect(onScrollSpy).toHaveBeenCalled();

      info2.unspy();
      onScrollSpy.calls.reset();

      window.dispatchEvent(new Event('scroll'));
      tick(SCROLL_EVENT_DELAY);
      expect(onScrollSpy).not.toHaveBeenCalled();
    }));

    it(`should only fire every ${SCROLL_EVENT_DELAY}ms`, fakeAsync(() => {
      scrollSpyService.spyOn([]);

      window.dispatchEvent(new Event('scroll'));
      tick(SCROLL_EVENT_DELAY - 2);
      expect(onScrollSpy).not.toHaveBeenCalled();

      window.dispatchEvent(new Event('scroll'));
      tick(1);
      expect(onScrollSpy).not.toHaveBeenCalled();

      window.dispatchEvent(new Event('scroll'));
      tick(1);
      expect(onScrollSpy).toHaveBeenCalledTimes(1);

      onScrollSpy.calls.reset();
      tick(SCROLL_EVENT_DELAY / 2);

      window.dispatchEvent(new Event('scroll'));
      tick(SCROLL_EVENT_DELAY - 2);
      expect(onScrollSpy).not.toHaveBeenCalled();

      window.dispatchEvent(new Event('scroll'));
      tick(1);
      expect(onScrollSpy).not.toHaveBeenCalled();

      window.dispatchEvent(new Event('scroll'));
      tick(1);
      expect(onScrollSpy).toHaveBeenCalledTimes(1);
    }));
  });

  describe('#onResize()', () => {
    it('should re-calibrate each `ScrollSpiedElementGroup`', () => {
      scrollSpyService.spyOn([]);
      scrollSpyService.spyOn([]);
      scrollSpyService.spyOn([]);

      const spiedElemGroups: ScrollSpiedElementGroup[] = (scrollSpyService as any).spiedElementGroups;
      const calibrateSpies = spiedElemGroups.map(group => spyOn(group, 'calibrate'));

      calibrateSpies.forEach(spy => expect(spy).not.toHaveBeenCalled());

      (scrollSpyService as any).onResize();
      calibrateSpies.forEach(spy => expect(spy).toHaveBeenCalled());
    });
  });

  describe('#onScroll()', () => {
    it('should propagate to each `ScrollSpiedElementGroup`', () => {
      scrollSpyService.spyOn([]);
      scrollSpyService.spyOn([]);
      scrollSpyService.spyOn([]);

      const spiedElemGroups: ScrollSpiedElementGroup[] = (scrollSpyService as any).spiedElementGroups;
      const onScrollSpies = spiedElemGroups.map(group => spyOn(group, 'onScroll'));

      onScrollSpies.forEach(spy => expect(spy).not.toHaveBeenCalled());

      (scrollSpyService as any).onScroll();
      onScrollSpies.forEach(spy => expect(spy).toHaveBeenCalled());
    });

    it('should first re-calibrate if the content height has changed', () => {
      const body = injector.get(DOCUMENT).body as any;

      scrollSpyService.spyOn([]);
      scrollSpyService.spyOn([]);
      scrollSpyService.spyOn([]);

      const spiedElemGroups: ScrollSpiedElementGroup[] = (scrollSpyService as any).spiedElementGroups;
      const onScrollSpies = spiedElemGroups.map(group => spyOn(group, 'onScroll'));
      const calibrateSpies = spiedElemGroups.map((group, i) => spyOn(group, 'calibrate')
                .and.callFake(() => expect(onScrollSpies[i]).not.toHaveBeenCalled()));

      calibrateSpies.forEach(spy => expect(spy).not.toHaveBeenCalled());
      onScrollSpies.forEach(spy => expect(spy).not.toHaveBeenCalled());

      // No content height change...
      (scrollSpyService as any).onScroll();
      calibrateSpies.forEach(spy => expect(spy).not.toHaveBeenCalled());
      onScrollSpies.forEach(spy => expect(spy).toHaveBeenCalled());

      onScrollSpies.forEach(spy => spy.calls.reset());
      body.scrollHeight = 100;

      // Viewport changed...
      (scrollSpyService as any).onScroll();
      calibrateSpies.forEach(spy => expect(spy).toHaveBeenCalled());
      onScrollSpies.forEach(spy => expect(spy).toHaveBeenCalled());
    });
  });
});
 constructor(protected injector: Injector) {
   this.tableColumn = this.injector.get(OTableColumnComponent);
 }
 beforeEach(inject([ Injector ], (injector: Injector) => {
     isSupported = injector.get(audioContextModuleIsSupported);
 }));
    describe('TranslateService', () => {
        let injector: Injector;
        let backend: MockBackend;
        let translate: TranslateService;
        let connection: MockConnection; // this will be set when a new connection is emitted from the backend.

        beforeEach(() => {
            injector = ReflectiveInjector.resolveAndCreate([
                HTTP_PROVIDERS,
                // Provide a mocked (fake) backend for Http
                provide(XHRBackend, {useClass: MockBackend}),
                TRANSLATE_PROVIDERS
            ]);
            backend = injector.get(XHRBackend);
            translate = injector.get(TranslateService);
            // sets the connection when someone tries to access the backend with an xhr request
            backend.connections.subscribe((c: MockConnection) => connection = c);
        });

        afterEach(() => {
            injector = undefined;
            backend = undefined;
            translate = undefined;
            connection = undefined;
        });

        it('is defined', () => {
            expect(TranslateService).toBeDefined();
            expect(translate).toBeDefined();
            expect(translate instanceof TranslateService).toBeTruthy();
        });

        it('should be able to get translations', () => {
            translate.use('en');

            // this will request the translation from the backend because we use a static files loader for TranslateService
            translate.get('TEST').subscribe((res: string) => {
                expect(res).toEqual('This is a test');
            });

            // mock response after the xhr request, otherwise it will be undefined
            mockBackendResponse(connection, '{"TEST": "This is a test", "TEST2": "This is another test"}');

            // this will request the translation from downloaded translations without making a request to the backend
            translate.get('TEST2').subscribe((res: string) => {
                expect(res).toEqual('This is another test');
            });
        });

        it('should be able to get an array translations', () => {
            var translations = {"TEST": "This is a test", "TEST2": "This is another test2"};
            translate.use('en');

            // this will request the translation from the backend because we use a static files loader for TranslateService
            translate.get(['TEST', 'TEST2']).subscribe((res: string) => {
                expect(res).toEqual(translations);
            });

            // mock response after the xhr request, otherwise it will be undefined
            mockBackendResponse(connection, JSON.stringify(translations));
        });

        it("should fallback to the default language", () => {
            translate.use('fr');

            translate.setDefaultLang('en');
            translate.setTranslation('en', {"TEST": "This is a test"});

            translate.get('TEST').subscribe((res: string) => {
                expect(res).toEqual('This is a test');
            });

            mockBackendResponse(connection, '{}');
        });

        it("should return the key when it doesn't find a translation", () => {
            translate.use('en');

            translate.get('TEST').subscribe((res: string) => {
                expect(res).toEqual('TEST');
            });

            mockBackendResponse(connection, '{}');
        });

        it("should return the key when you haven't defined any translation", () => {
            translate.get('TEST').subscribe((res: string) => {
                expect(res).toEqual('TEST');
            });
        });

        it('should be able to get translations with params', () => {
            translate.use('en');

            translate.get('TEST', {param: 'with param'}).subscribe((res: string) => {
                expect(res).toEqual('This is a test with param');
            });

            mockBackendResponse(connection, '{"TEST": "This is a test {{param}}"}');
        });

        it('should be able to get translations with nested params', () => {
            translate.use('en');

            translate.get('TEST', {param: {value: 'with param'}}).subscribe((res: string) => {
                expect(res).toEqual('This is a test with param');
            });

            mockBackendResponse(connection, '{"TEST": "This is a test {{param.value}}"}');
        });

        it('should throw if you forget the key', () => {
            translate.use('en');

            expect(() => {
                translate.get(undefined);
            }).toThrowError('Parameter "key" required');
        });

        it('should be able to get translations with nested keys', () => {
            translate.use('en');

            translate.get('TEST.TEST').subscribe((res: string) => {
                expect(res).toEqual('This is a test');
            });

            mockBackendResponse(connection, '{"TEST": {"TEST": "This is a test"}, "TEST2": {"TEST2": {"TEST2": "This is another test"}}}');

            translate.get('TEST2.TEST2.TEST2').subscribe((res: string) => {
                expect(res).toEqual('This is another test');
            });
        });

        it("shouldn't do a request to the backend if you set the translation yourself", (done: Function) => {
            translate.setTranslation('en', {"TEST": "This is a test"});
            translate.use('en');

            translate.get('TEST').subscribe((res: string) => {
                expect(res).toEqual('This is a test');
                expect(connection).not.toBeDefined();
                done();
            });
        });

        it('should be able to get instant translations', () => {
            translate.setTranslation('en', {"TEST": "This is a test"});
            translate.use('en');

            expect(translate.instant('TEST')).toEqual('This is a test');
        });

        it('should be able to get instant translations of an array', () => {
            var translations = {"TEST": "This is a test", "TEST2": "This is a test2"};
            translate.setTranslation('en', translations);
            translate.use('en');

            expect(translate.instant(['TEST', 'TEST2'])).toEqual(translations);
        });

        it('should return the key if instant translations are not available', () => {
            translate.setTranslation('en', {"TEST": "This is a test"});
            translate.use('en');

            expect(translate.instant('TEST2')).toEqual('TEST2');
        });

        it('should trigger an event when the lang changes', () => {
            var tr = {"TEST": "This is a test"};
            translate.setTranslation('en', tr);
            translate.onLangChange.subscribe((event: LangChangeEvent) => {
                expect(event.lang).toBe('en');
                expect(event.translations).toEqual(tr);
            });
            translate.use('en');
        });

        it('should be able to reset a lang', (done: Function) => {
            translate.use('en');
            spyOn(connection, 'mockRespond').and.callThrough();

            // this will request the translation from the backend because we use a static files loader for TranslateService
            translate.get('TEST').subscribe((res: string) => {
                expect(res).toEqual('This is a test');
                expect(connection.mockRespond).toHaveBeenCalledTimes(1);

                // reset the lang as if it was never initiated
                translate.resetLang('en');

                expect(translate.instant('TEST')).toEqual('TEST');

                // use set timeout because no request is really made and we need to trigger zone to resolve the observable
                setTimeout(() => {
                    translate.get('TEST').subscribe((res: string) => {
                        expect(res).toEqual('TEST'); // because the loader is "pristine" as if it was never called
                        expect(connection.mockRespond).toHaveBeenCalledTimes(1);
                        done();
                    });
                }, 10);
            });

            // mock response after the xhr request, otherwise it will be undefined
            mockBackendResponse(connection, '{"TEST": "This is a test"}');
        });

        it('should be able to reload a lang', () => {
            translate.use('en');

            // this will request the translation from the backend because we use a static files loader for TranslateService
            translate.get('TEST').subscribe((res: string) => {
                expect(res).toEqual('This is a test');

                // reset the lang as if it was never initiated
                translate.reloadLang('en').subscribe((res: string) => {
                    expect(translate.instant('TEST')).toEqual('This is a test 2');
                });

                mockBackendResponse(connection, '{"TEST": "This is a test 2"}');
            });

            // mock response after the xhr request, otherwise it will be undefined
            mockBackendResponse(connection, '{"TEST": "This is a test"}');
        });
    });
Example #23
0
 it('works', () => { expect(injector.get(AotService) instanceof AotService).toBeTruthy(); });
    describe('MissingTranslationHandler', () => {
        let injector: Injector;
        let backend: MockBackend;
        let translate: TranslateService;
        let connection: MockConnection; // this will be set when a new connection is emitted from the backend.
        let missingTranslationHandler: MissingTranslationHandler;

        class Missing implements MissingTranslationHandler {
            handle(key: string) {
                return "handled";
            }
        }

        class MissingObs implements MissingTranslationHandler {
            handle(key: string): Observable<any> {
                return Observable.of(`handled: ${key}`);
            }
        }

        let prepare = ((handlerClass: Function) => {
            injector = ReflectiveInjector.resolveAndCreate([
                HTTP_PROVIDERS,
                // Provide a mocked (fake) backend for Http
                provide(XHRBackend, {useClass: MockBackend}),
                TRANSLATE_PROVIDERS,
                provide(MissingTranslationHandler, {useClass: handlerClass})
            ]);
            backend = injector.get(XHRBackend);
            translate = injector.get(TranslateService);
            missingTranslationHandler = injector.get(MissingTranslationHandler);
            // sets the connection when someone tries to access the backend with an xhr request
            backend.connections.subscribe((c: MockConnection) => connection = c);
        });

        afterEach(() => {
            injector = undefined;
            backend = undefined;
            translate = undefined;
            connection = undefined;
            missingTranslationHandler = undefined;
        });

        it('should use the MissingTranslationHandler when the key does not exist', () => {
            prepare(Missing);
            translate.use('en');
            spyOn(missingTranslationHandler, 'handle').and.callThrough();

            translate.get('nonExistingKey').subscribe((res: string) => {
                expect(missingTranslationHandler.handle).toHaveBeenCalledWith('nonExistingKey');
                expect(res).toEqual('handled');
            });

            // mock response after the xhr request, otherwise it will be undefined
            mockBackendResponse(connection, '{"TEST": "This is a test"}');
        });

        it('should return the key when using MissingTranslationHandler & the handler returns nothing', () => {
            class MissingUndef implements MissingTranslationHandler {
                handle(key: string) {
                }
            }

            prepare(MissingUndef);
            translate.use('en');
            spyOn(missingTranslationHandler, 'handle').and.callThrough();

            translate.get('nonExistingKey').subscribe((res: string) => {
                expect(missingTranslationHandler.handle).toHaveBeenCalledWith('nonExistingKey');
                expect(res).toEqual('nonExistingKey');
            });

            // mock response after the xhr request, otherwise it will be undefined
            mockBackendResponse(connection, '{"TEST": "This is a test"}');
        });

        it('should not call the MissingTranslationHandler when the key exists', () => {
            prepare(Missing);
            translate.use('en');
            spyOn(missingTranslationHandler, 'handle').and.callThrough();

            translate.get('TEST').subscribe(() => {
                expect(missingTranslationHandler.handle).not.toHaveBeenCalled();
            });

            // mock response after the xhr request, otherwise it will be undefined
            mockBackendResponse(connection, '{"TEST": "This is a test"}');
        });

        it('should use the MissingTranslationHandler when the key does not exist & we use instant translation', () => {
            prepare(Missing);
            translate.use('en');
            spyOn(missingTranslationHandler, 'handle').and.callThrough();

            expect(translate.instant('nonExistingKey')).toEqual('handled');
            expect(missingTranslationHandler.handle).toHaveBeenCalledWith('nonExistingKey');
        });

        it('should wait for the MissingTranslationHandler when it returns an observable & we use get', () => {
            prepare(MissingObs);
            translate.use('en');
            spyOn(missingTranslationHandler, 'handle').and.callThrough();

            translate.get('nonExistingKey').subscribe((res: string) => {
                expect(missingTranslationHandler.handle).toHaveBeenCalledWith('nonExistingKey');
                expect(res).toEqual('handled: nonExistingKey');
            });

            // mock response after the xhr request, otherwise it will be undefined
            mockBackendResponse(connection, '{"TEST": "This is a test"}');
        });

        it('should wait for the MissingTranslationHandler when it returns an observable & we use get with an array', () => {
            let translations = {
                nonExistingKey1: 'handled: nonExistingKey1',
                nonExistingKey2: 'handled: nonExistingKey2',
                nonExistingKey3: 'handled: nonExistingKey3'
            };

            prepare(MissingObs);
            translate.use('en');
            spyOn(missingTranslationHandler, 'handle').and.callThrough();

            translate.get(Object.keys(translations)).subscribe((res: string) => {
                expect(missingTranslationHandler.handle).toHaveBeenCalledTimes(3);
                expect(res).toEqual(translations);
            });

            // mock response after the xhr request, otherwise it will be undefined
            mockBackendResponse(connection, '{"TEST": "This is a test"}');
        });

        it('should not wait for the MissingTranslationHandler when it returns an observable & we use instant', () => {
            prepare(MissingObs);
            translate.use('en');
            spyOn(missingTranslationHandler, 'handle').and.callThrough();

            expect(translate.instant('nonExistingKey')).toEqual('nonExistingKey');

            // mock response after the xhr request, otherwise it will be undefined
            mockBackendResponse(connection, '{"TEST": "This is a test"}');
        });

        it('should not wait for the MissingTranslationHandler when it returns an observable & we use instant with an array', () => {
            let translations = {
                nonExistingKey1: 'handled: nonExistingKey1',
                nonExistingKey2: 'handled: nonExistingKey2',
                nonExistingKey3: 'handled: nonExistingKey3'
            };

            prepare(MissingObs);
            translate.use('en');
            spyOn(missingTranslationHandler, 'handle').and.callThrough();

            expect(translate.instant(Object.keys(translations))).toEqual({
                nonExistingKey1: 'nonExistingKey1',
                nonExistingKey2: 'nonExistingKey2',
                nonExistingKey3: 'nonExistingKey3'
            });

            // mock response after the xhr request, otherwise it will be undefined
            mockBackendResponse(connection, '{"TEST": "This is a test"}');
        });
    });
Example #25
0
 authenticate(name: string, userData?: any): Observable<Response> {
     // var injector = Injector.resolveAndCreate([Oauth1, Oauth2]);
     let provider: Oauth1 | Oauth2 = this.config.providers[name].type === '1.0' ? this.injector.get(Oauth1) : this.injector.get(Oauth2);
     return provider.open(this.config.providers[name], userData || {})
         .map((response: Response) => {
             // this is for a scenario when someone wishes to opt out from
             // satellizer's magic by doing authorization code exchange and
             // saving a token manually.
             if (this.config.providers[name].url) {
                 this.shared.setToken(response);
             }
             return response;
         });
 }
 var prepare = (injector: Injector) => {
     backend = injector.get(XHRBackend);
     translate = injector.get(TranslateService);
     // sets the connection when someone tries to access the backend with an xhr request
     backend.connections.subscribe((c: MockConnection) => connection = c);
 };
 setTimeout(() => (this.alertService = injector.get(JhiAlertService)));
 ]).then((injector: Injector) => {
   expect(injector.get(token1)).toEqual(tokenValue1);
   expect(injector.get(token2)).toEqual(tokenValue2);
   async.done();
 });
Example #29
0
 expect(() => injector.get('invalidToken')).toThrowError();
 constructor(injector: Injector) {
     this.parent = injector.get(ArticleContentHotspotComponent);
     this.article = this.parent.article;
 }