@angular/cdk/overlay#OverlayContainer TypeScript Examples

The following examples show how to use @angular/cdk/overlay#OverlayContainer. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: utils.service.ts    From tuxedo-control-center with GNU General Public License v3.0 7 votes vote down vote up
constructor(
    private sysfs: SysFsService,
    private electron: ElectronService,
    private decimalPipe: DecimalPipe,
    public overlayContainer: OverlayContainer,
    @Inject(LOCALE_ID) localeId) {
      this.localeId = localeId;
      this.languageMap = {};
      for (const lang of this.getLanguagesMenuArray()) {
        this.languageMap[lang.id] = lang;
      }

      if (localStorage.getItem('themeClass')) {
        this.themeClass = new BehaviorSubject<string>(localStorage.getItem('themeClass'));
      } else {
        this.themeClass = new BehaviorSubject<string>('light-theme');
      }
    }
Example #2
Source File: app.component.ts    From bitcoin-s-ts with MIT License 6 votes vote down vote up
constructor(private titleService: Title, private translate: TranslateService, public router: Router,
    public messageService: MessageService, private snackBar: MatSnackBar, public authService: AuthService,
    private oracleStateService: OracleStateService, private overlay: OverlayContainer) {
    this.loggedIn$ = this.authService.loggedIn.subscribe(r => {
      console.debug('loggedIn')
      this.onLogin()
    })
    this.loggedOut$ = this.authService.loggedOut.subscribe(r => {
      console.debug('loggedOut')
      this.onLogout()
    })
    this.authService.initialize()
  }
Example #3
Source File: custom-overlay-container.ts    From spurtcommerce with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Injectable()
export class CustomOverlayContainer extends OverlayContainer {
    _createContainer(): void {
        const container = document.createElement('div');
        container.classList.add('cdk-overlay-container');
        document.getElementById('app').appendChild(container);
        this._containerElement = container;
    }
}
Example #4
Source File: settings.effects.ts    From enterprise-ng-2020-workshop with MIT License 6 votes vote down vote up
constructor(
    private actions$: Actions,
    private store: Store<State>,
    private router: Router,
    private overlayContainer: OverlayContainer,
    private localStorageService: LocalStorageService,
    private titleService: TitleService,
    private animationsService: AnimationsService,
    private translateService: TranslateService,
    private ngZone: NgZone
  ) {}
Example #5
Source File: theming.service.ts    From EXOS-Core with MIT License 6 votes vote down vote up
constructor(
        private readonly log: Logger,
        private readonly overlayContainer: OverlayContainer
    ) {

        if (!Theming.singletonInstance) {
            Theming.singletonInstance = this;
        }

        return Theming.singletonInstance;

    }
Example #6
Source File: app.component.ts    From attack-workbench-frontend with Apache License 2.0 6 votes vote down vote up
constructor(private overlayContainer: OverlayContainer,
                private sidebarService: SidebarService,
                private titleService: TitleService,
                private logger: NGXLogger) { //note: this isn't used directly, but it MUST be imported to work properly

        if (hasCookie("theme")) {
            this.setTheme(getCookie("theme"))
        } else {
            this.setTheme("light");
        }
        initLogger(logger);
    }
Example #7
Source File: theming.service.ts    From blockcore-hub with MIT License 6 votes vote down vote up
constructor(
        private readonly log: Logger,
        private readonly overlayContainer: OverlayContainer
    ) {

        if (!Theming.singletonInstance) {
            Theming.singletonInstance = this;
        }

        return Theming.singletonInstance;

    }
Example #8
Source File: app.component.ts    From bitcoin-s-ts with MIT License 6 votes vote down vote up
constructor(private titleService: Title, private translate: TranslateService, public messageService: MessageService, 
    private overlay: OverlayContainer, private router: Router,
    public walletStateService: WalletStateService, private dlcService: DLCService, private dlcFileService: DLCFileService,
    private websocketService: WebsocketService, public authService: AuthService,
    private darkModeService: DarkModeService) {
    
    this.loggedIn$ = this.authService.loggedIn.subscribe(r => {
      console.debug('loggedIn')
      this.onLogin()
    })
    this.loggedOut$ = this.authService.loggedOut.subscribe(r => {
      console.debug('loggedOut')
      this.onLogout()
    })
    this.authService.initialize()
  }
Example #9
Source File: home.component.ts    From VIR with MIT License 6 votes vote down vote up
constructor(private router: Router,
              private overlayContainer: OverlayContainer,
              private dialog: MatDialog,
              private readonly fsUtil: FsUtil,
              private readonly electronService: ElectronService,
              public readonly dataStore: DataStore,
              public readonly dataAnalyzer: DataAnalyzer,
              public readonly clock: Clock,
              private readonly snackBar: MatSnackBar,
              private readonly changeDetectorRef: ChangeDetectorRef) {
    this.setActiveTheme(this.activeTheme, this.enableDarkMode)
    this.sideBarDayID = dataStore.getCurrentDayID()
  }
Example #10
Source File: titlebar.component.spec.ts    From WowUp with GNU General Public License v3.0 5 votes vote down vote up
describe("TitlebarComponent", () => {
  let component: TitlebarComponent;
  let fixture: ComponentFixture<TitlebarComponent>;
  let electronServiceSpy: any;
  let wowUpServiceSpy: any;

  beforeEach(async () => {
    electronServiceSpy = jasmine.createSpyObj("ElectronService", ["on"], {
      windowMaximized$: new BehaviorSubject(false).asObservable(),
    });
    wowUpServiceSpy = jasmine.createSpyObj("WowUpService", [""], {
      currentTheme: "horde ofc",
    });

    await TestBed.configureTestingModule({
      declarations: [TitlebarComponent],
      imports: [
        MatModule,
        NoopAnimationsModule,
        HttpClientModule,
        TranslateModule.forRoot({
          loader: {
            provide: TranslateLoader,
            useFactory: httpLoaderFactory,
            deps: [HttpClient],
          },
          compiler: {
            provide: TranslateCompiler,
            useClass: TranslateMessageFormatCompiler,
          },
        }),
      ],
    })
      .overrideComponent(TitlebarComponent, {
        set: {
          providers: [
            OverlayContainer,
            { provide: ElectronService, useValue: electronServiceSpy },
            { provide: WowUpService, useValue: wowUpServiceSpy },
          ],
        },
      })
      .compileComponents();

    fixture = TestBed.createComponent(TitlebarComponent);
    component = fixture.componentInstance;

    fixture.detectChanges();
  });

  it("should create", () => {
    expect(component).toBeTruthy();
  });
});
Example #11
Source File: app.component.ts    From angular-dark-mode with MIT License 5 votes vote down vote up
constructor(private dialog: MatDialog, private overlay: OverlayContainer) { }
Example #12
Source File: default.module.ts    From spurtcommerce with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@NgModule({
    imports: [
        BrowserModule,
        BrowserAnimationsModule,
        HttpClientModule,
        NgxSpinnerModule,
        SharedModule,
        ComponentsModule,
        EffectsModule.forRoot([ListsEffect]),
        StoreModule.forRoot(reducers, {metaReducers}),
        EffectsModule.forRoot([ListsEffect, WishlistEffect]),
        ShareButtonModule.withConfig({
            debug: true
        }),
        AgmCoreModule.forRoot({
            apiKey: 'AIzaSyCfuTV5tYInC-Mj6YJ9LzRocVOdn3yCUGM'
        }),
        DefaultRoutingModule
    ],
    declarations: [
        DefaultComponent,
        NotFoundComponent,
        DetailPageComponent,
        CONTAINERS.LayoutContainerComponent,
        UnderDevelopingComponent
    ],
    providers: [
        AppSettings,
        LayoutAuthGuard,
        AuthGuard,
        ConfigService,
        {provide: OverlayContainer, useClass: CustomOverlayContainer},
        {provide: MAT_MENU_SCROLL_STRATEGY, useFactory: menuScrollStrategy, deps: [Overlay]},
        {
            provide: HTTP_INTERCEPTORS,
            useClass: RequestInterceptor,
            multi: true
        },
        {provide: APP_BASE_HREF, useValue: ''},
        ListsSandbox,
        ListsService,
        WishlistSandbox,
        WishlistService
    ],
    bootstrap: [DefaultComponent]
})
export class DefaultModule {
}
Example #13
Source File: fake-async-harness-environment.spec.ts    From s-libs with MIT License 5 votes vote down vote up
describe('FakeAsyncHarnessEnvironment', () => {
  @Component({
    template: `
      <button mat-button (click)="clicked = true">{{ clicked }}</button>
    `,
  })
  class ClickableButtonComponent {
    clicked = false;
  }

  it('runs asynchronous events that are due automatically', () => {
    const ctx = new ComponentContext(ClickableButtonComponent);
    ctx.run(async () => {
      const button = await ctx.getHarness(MatButtonHarness);
      await button.click();
      expect(await button.getText()).toBe('true');
    });
  });

  it('does not flush timeouts that are not yet due', () => {
    class SnackBarContext extends ComponentContext<ClickableButtonComponent> {
      constructor() {
        super(ClickableButtonComponent, {
          imports: [MatSnackBarModule, NoopAnimationsModule],
        });
      }

      protected override cleanUp(): void {
        this.inject(OverlayContainer).ngOnDestroy();
        this.tick(5000);
        super.cleanUp();
      }
    }

    const ctx = new SnackBarContext();
    ctx.run(async () => {
      ctx
        .inject(MatSnackBar)
        // When using the built-in TestBedHarnessEnvironment, fetching the harness would flush the duration and it would disappear before being selected
        .open('Hello, snackbar!', 'OK', { duration: 5000 });
      expect(await ctx.getHarness(MatSnackBarHarness)).toBeDefined();
    });
  });
});
Example #14
Source File: app.component.ts    From WowUp with GNU General Public License v3.0 5 votes vote down vote up
public constructor(
    private _addonService: AddonService,
    private _addonProviderService: AddonProviderFactory,
    private _analyticsService: AnalyticsService,
    private _cdRef: ChangeDetectorRef,
    private _dialog: MatDialog,
    private _fileService: FileService,
    private _preferenceStore: PreferenceStorageService,
    private _snackbarService: SnackbarService,
    private _translateService: TranslateService,
    private _warcraftInstallationService: WarcraftInstallationService,
    private _wowupAddonService: WowUpAddonService,
    private _zoomService: ZoomService,
    private _wowUpProtocolService: WowUpProtocolService,
    public electronService: ElectronService,
    public overlayContainer: OverlayContainer,
    public sessionService: SessionService,
    public wowUpService: WowUpService
  ) {
    this._warcraftInstallationService.wowInstallations$
      .pipe(
        first((installations) => installations.length > 0),
        switchMap(() => from(this.initializeAutoUpdate()))
      )
      .subscribe();

    this.electronService.appUpdate$.subscribe((evt) => {
      if (evt.state === AppUpdateState.Error) {
        if (evt.error.indexOf("dev-app-update.yml") === -1) {
          this._snackbarService.showErrorSnackbar("APP.WOWUP_UPDATE.UPDATE_ERROR");
        }
      } else if (evt.state === AppUpdateState.Downloaded) {
        // Force the user to update when one is ready
        const dialogRef = this._dialog.open(AlertDialogComponent, {
          minWidth: 250,
          disableClose: true,
          data: {
            title: this._translateService.instant("APP.WOWUP_UPDATE.INSTALL_TITLE"),
            message: this._translateService.instant("APP.WOWUP_UPDATE.SNACKBAR_TEXT"),
            positiveButton: "APP.WOWUP_UPDATE.DOWNLOADED_TOOLTIP",
            positiveButtonColor: "primary",
            positiveButtonStyle: "raised",
          },
        });

        dialogRef
          .afterClosed()
          .pipe(first())
          .subscribe(() => {
            this.wowUpService.installUpdate();
          });
      }
    });

    this._wowUpProtocolService.initialize();
  }
Example #15
Source File: settings.effects.spec.ts    From enterprise-ng-2020-workshop with MIT License 5 votes vote down vote up
describe('SettingsEffects', () => {
  let router: any;
  let localStorageService: jasmine.SpyObj<LocalStorageService>;
  let overlayContainer: jasmine.SpyObj<OverlayContainer>;
  let titleService: jasmine.SpyObj<TitleService>;
  let animationsService: jasmine.SpyObj<AnimationsService>;
  let translateService: jasmine.SpyObj<TranslateService>;
  let store: jasmine.SpyObj<Store<AppState>>;
  let ngZone: jasmine.SpyObj<NgZone>;

  beforeEach(() => {
    router = {
      routerState: {
        snapshot: {}
      },
      events: {
        pipe() {}
      }
    };
    localStorageService = jasmine.createSpyObj('LocalStorageService', [
      'setItem'
    ]);
    overlayContainer = jasmine.createSpyObj('OverlayContainer', [
      'getContainerElement'
    ]);
    titleService = jasmine.createSpyObj('TitleService', ['setTitle']);
    animationsService = jasmine.createSpyObj('AnimationsService', [
      'updateRouteAnimationType'
    ]);
    translateService = jasmine.createSpyObj('TranslateService', ['use']);
    store = jasmine.createSpyObj('store', ['pipe']);
    ngZone = jasmine.createSpyObj('mockNgZone', ['run', 'runOutsideAngular']);
    ngZone.run.and.callFake((fn) => fn());
  });

  it('should call methods on LocalStorageService for PERSIST action', () => {
    scheduler.run((helpers) => {
      const { cold } = helpers;

      const settings: SettingsState = {
        language: 'en',
        pageAnimations: true,
        elementsAnimations: true,
        theme: 'default',
        nightTheme: 'default',
        autoNightMode: false,
        stickyHeader: false,
        pageAnimationsDisabled: true,
        hour: 12
      };
      store.pipe.and.returnValue(of(settings));
      const persistAction = actionSettingsChangeTheme({ theme: 'DEFAULT' });
      const source = cold('a', { a: persistAction });
      const actions = new Actions(source);
      const effect = new SettingsEffects(
        actions,
        store,
        router,
        overlayContainer,
        localStorageService,
        titleService,
        animationsService,
        translateService,
        ngZone
      );

      effect.persistSettings.subscribe(() => {
        expect(localStorageService.setItem).toHaveBeenCalledWith(
          SETTINGS_KEY,
          settings
        );
      });
    });
  });
});
Example #16
Source File: message.service.spec.ts    From alauda-ui with MIT License 5 votes vote down vote up
describe('MessageService', () => {
  let fixture: ComponentFixture<TestComponent>;
  let ocEl: HTMLElement;
  let messageService: MessageService;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [TestModule],
      providers: [
        {
          provide: MESSAGE_CONFIG,
          useValue: {
            duration: 10_000,
            maxStack: 3,
          },
        },
      ],
    });

    fixture = TestBed.createComponent(TestComponent);

    inject(
      [OverlayContainer, MessageService],
      (overlayContainer: OverlayContainer, service: MessageService) => {
        ocEl = overlayContainer.getContainerElement();
        messageService = service;
      },
    )();
  });

  it('should work with global config', () => {
    messageService.success('Message success0');
    fixture.detectChanges();
    messageService.success('Message success1');
    fixture.detectChanges();
    messageService.success('Message success2');
    fixture.detectChanges();
    messageService.success('Message success3');
    fixture.detectChanges();
    messageService.success('Message success4');
    fixture.detectChanges();
    messageService.success('Message success5');
    fixture.detectChanges();

    expect(ocEl.querySelectorAll('.aui-message').length).toEqual(6);
  });

  it('should show a success Message with  string', () => {
    messageService.success('Message success');
    fixture.detectChanges();
    expect(ocEl.querySelector('.aui-message')).not.toBeNull();
    expect(ocEl.querySelector('.aui-message').classList).toContain(
      'aui-message--success',
    );
    expect(ocEl.querySelector('.aui-message__content').innerHTML).toContain(
      'Message success',
    );
  });

  it('should show a success Message with object', () => {
    messageService.success({
      content: 'Message success object',
      duration: 5,
    });
    fixture.detectChanges();
    expect(ocEl.querySelector('.aui-message')).not.toBeNull();
    expect(ocEl.querySelector('.aui-message').classList).toContain(
      'aui-message--success',
    );
    expect(ocEl.querySelector('.aui-message__content').innerHTML).toContain(
      'Message success object',
    );
  });
});
Example #17
Source File: app.component.ts    From App with MIT License 5 votes vote down vote up
constructor(
		@Inject(PLATFORM_ID) platformId: any,
		iconRegistry: MatIconRegistry,
		sanitizer: DomSanitizer,
		appService: AppService,
		titleService: Title,
		localStorageSvc: LocalStorageService,
		private windowRef: WindowRef,
		private sw: SwUpdate,
		private dialog: MatDialog,
		private location: Location,
		private router: Router,
		private overlayRef: OverlayContainer,
		public viewportService: ViewportService
	) {
		// Check if platform is browser
		AppComponent.isBrowser.next(isPlatformBrowser(platformId));

		for (const iconRef of iconList) {
			iconRegistry.addSvgIcon(
				iconRef[0],
				sanitizer.bypassSecurityTrustResourceUrl(`assets/${iconRef[1]}`)
			);
		}

		// Set page title
		{
			router.events.pipe( // Handle "ActivationStart" router event
				filter(ev => ev instanceof ActivationStart),
				map(ev => ev as ActivationStart),

				// Find variables and omit them from the title.
				// Components can call AppService.pushTitleAttributes() to update them
				tap(ev => {
					const title: string = '7TV - ' + (ev.snapshot.data?.title ?? 'Untitled Page' as string);

					appService.pageTitleSnapshot = String(title);
					titleService.setTitle(`${title?.replace(AppService.PAGE_ATTR_REGEX, '')}`);
				})
			).subscribe();
		}

		this.setTheme();

		if (isPlatformBrowser(platformId)) {
			localStorageSvc.storage = localStorage;
		}
	}
Example #18
Source File: status-bar.component.spec.ts    From alauda-ui with MIT License 5 votes vote down vote up
describe('Status Bar', () => {
  let fixture: ComponentFixture<TestComponent>;
  let ocEl: HTMLElement;
  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [StatusBarModule],
      declarations: [TestComponent],
    });

    fixture = TestBed.createComponent(TestComponent);
    fixture.detectChanges();

    inject([OverlayContainer], (overlayContainer: OverlayContainer) => {
      ocEl = overlayContainer.getContainerElement();
    })();
  });

  it('should match snapshot', fakeAsync(() => {
    expect(fixture).toMatchSnapshot();

    const chunk = fixture.debugElement.query(
      By.css('aui-status-bar .aui-status-bar__chunk'),
    ).nativeElement as HTMLElement;
    chunk.dispatchEvent(new Event('mouseenter'));
    tick(50);

    fixture.detectChanges();
    expect(fixture).toMatchSnapshot();
    expect(ocEl).toMatchSnapshot();
  }));

  it('should onChunkClick called once', () => {
    const mockFn = jest.fn();

    fixture.componentInstance.onChunkClick = mockFn;

    const chunk = fixture.debugElement.query(
      By.css('aui-status-bar .aui-status-bar__chunk'),
    ).nativeElement as HTMLElement;
    chunk.dispatchEvent(new Event('click'));

    expect(mockFn.mock.calls.length).toBe(1);
    expect(mockFn.mock.calls[0][0]).toEqual({
      scale: 0.1,
      type: StatusType.Info,
      class: 'custom-class',
    });
  });
});
Example #19
Source File: dialog.service.spec.ts    From alauda-ui with MIT License 4 votes vote down vote up
describe('DialogService', () => {
  let fixture: ComponentFixture<TestComponent>;
  let ocEl: HTMLElement;
  let dialogService: DialogService;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [TestModule],
    });

    fixture = TestBed.createComponent(TestComponent);

    inject(
      [OverlayContainer, DialogService],
      (overlayContainer: OverlayContainer, service: DialogService) => {
        ocEl = overlayContainer.getContainerElement();
        dialogService = service;
      },
    )();
  });

  it('should open dialog with component portal', () => {
    dialogService.open(DialogContentComponent, {
      size: DialogSize.Large,
    });

    fixture.detectChanges();

    expect(ocEl.querySelector('.aui-dialog')).not.toBeNull();
    expect(ocEl.querySelector('.aui-dialog').classList).toContain(
      'aui-dialog--large',
    );
    expect(
      ocEl.querySelector('.aui-dialog>test-dialog-content'),
    ).not.toBeNull();
  });

  it('should be closed by click cancel button', () => {
    const dialogRef = dialogService.open(DialogContentComponent);
    dialogRef.afterClosed().subscribe(result => {
      expect(result).toBeFalsy();
      expect(ocEl.querySelector('aui-dialog')).toBeNull();
    });

    fixture.detectChanges();
    ocEl.querySelector('#cancel').dispatchEvent(new Event('click'));
  });

  it('should open dialog with template portal', () => {
    const ins = fixture.componentInstance;
    dialogService.open(ins.templateRef);
    fixture.detectChanges();

    expect(ocEl.querySelector('.aui-dialog button').innerHTML).toContain(
      'close',
    );
  });

  it('should be closed by click close button', () =>
    new Promise<void>(resolve => {
      const ins = fixture.componentInstance;
      ins.result = 'result';
      dialogService
        .open(ins.templateRef)
        .afterClosed()
        .subscribe(result => {
          expect(result).toBe('result');
          expect(ocEl.querySelector('aui-dialog')).toBeNull();
          resolve();
        });
      fixture.detectChanges();
      ocEl.querySelector('#close').dispatchEvent(new Event('click'));
      fixture.detectChanges();
    }));

  it('should open confirm dialog and invoke confirm callback', () =>
    new Promise<void>(resolve => {
      dialogService
        .confirm({
          title: 'title',
          content: 'content',
        })
        .then(() => {
          expect(ocEl.querySelector('aui-dialog')).toBeNull();
          resolve();
        });
      fixture.detectChanges();

      ocEl
        .querySelector('.aui-confirm-dialog__confirm-button')
        .dispatchEvent(new Event('click'));
    }));

  it('should open confirm dialog and invoke cancel callback', () =>
    new Promise<void>(resolve => {
      dialogService
        .confirm({
          title: 'custom title',
          content: 'custom content',
        })
        .catch(() => {
          // eslint-disable-next-line jest/no-conditional-expect
          expect(ocEl.querySelector('aui-dialog')).toBeNull();
          resolve();
        });
      fixture.detectChanges();

      expect(
        ocEl.querySelector('.aui-confirm-dialog__title').innerHTML,
      ).toContain('custom title');
      expect(
        ocEl.querySelector('.aui-confirm-dialog__content').innerHTML,
      ).toContain('custom content');
      ocEl
        .querySelector('.aui-confirm-dialog__cancel-button')
        .dispatchEvent(new Event('click'));
    }));

  it('should before confirm work correctly', () =>
    new Promise<void>(resolve => {
      const t1 = Date.now();
      dialogService
        .confirm({
          title: '',
          beforeConfirm: resolve => {
            setTimeout(resolve, 100);
          },
        })
        .then(() => {
          const t2 = Date.now();
          expect(t2 - t1).toBeGreaterThanOrEqual(100);
          resolve();
        });
      fixture.detectChanges();

      const confirmBtn: HTMLButtonElement = ocEl.querySelector(
        '.aui-confirm-dialog__confirm-button',
      );
      confirmBtn.dispatchEvent(new Event('click'));
      fixture.detectChanges();

      expect(confirmBtn.className).toContain('isLoading');
      expect(confirmBtn.disabled).toBeTruthy();
    }));

  it('should before confirm observable work correctly', () =>
    new Promise<void>(resolve => {
      const t1 = Date.now();
      dialogService
        .confirm({
          title: '',
          beforeConfirm: () => timer(100, 100),
        })
        // eslint-disable-next-line sonarjs/no-identical-functions
        .then(() => {
          const t2 = Date.now();
          expect(t2 - t1).toBeGreaterThanOrEqual(100);
          resolve();
        });
      fixture.detectChanges();

      const confirmBtn: HTMLButtonElement = ocEl.querySelector(
        '.aui-confirm-dialog__confirm-button',
      );
      confirmBtn.dispatchEvent(new Event('click'));
      fixture.detectChanges();

      expect(confirmBtn.className).toContain('isLoading');
      expect(confirmBtn.disabled).toBeTruthy();
    }));

  it('should before cancel work correctly', () =>
    new Promise<void>(resolve => {
      const t1 = Date.now();
      dialogService
        .confirm({
          title: '',
          beforeCancel: resolve => {
            setTimeout(resolve, 100);
          },
        })
        // eslint-disable-next-line sonarjs/no-identical-functions
        .catch(() => {
          const t2 = Date.now();
          // eslint-disable-next-line jest/no-conditional-expect
          expect(t2 - t1).toBeGreaterThanOrEqual(100);
          resolve();
        });
      fixture.detectChanges();

      const cancelBtn: HTMLButtonElement = ocEl.querySelector(
        '.aui-confirm-dialog__cancel-button',
      );
      cancelBtn.dispatchEvent(new Event('click'));
      fixture.detectChanges();

      expect(cancelBtn.className).toContain('isLoading');
      expect(cancelBtn.disabled).toBeTruthy();
    }));

  it('should before cancel observable work correctly', () =>
    new Promise<void>(resolve => {
      const t1 = Date.now();
      dialogService
        .confirm({
          title: '',
          beforeCancel: () => timer(100),
        })
        // eslint-disable-next-line sonarjs/no-identical-functions
        .catch(() => {
          const t2 = Date.now();
          // eslint-disable-next-line jest/no-conditional-expect
          expect(t2 - t1).toBeGreaterThanOrEqual(100);
          resolve();
        });
      fixture.detectChanges();

      // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion -- no idea
      const cancelBtn = ocEl.querySelector(
        '.aui-confirm-dialog__cancel-button',
      ) as HTMLButtonElement;
      cancelBtn.dispatchEvent(new Event('click'));
      fixture.detectChanges();

      expect(cancelBtn.className).toContain('isLoading');
      expect(cancelBtn.disabled).toBeTruthy();
    }));

  it('should before confirm callback could prevent close event', fakeAsync(() => {
    dialogService
      .confirm({
        title: '',
        beforeConfirm: (_, reject) => {
          setTimeout(reject, 100);
        },
      })
      .then(() => {
        throw new Error('confirm dialog should not be closed');
      })
      .catch(() => {
        throw new Error('confirm dialog should not be closed');
      });
    fixture.detectChanges();

    const confirmBtn: HTMLButtonElement = ocEl.querySelector(
      '.aui-confirm-dialog__confirm-button',
    );
    const cancelBtn: HTMLButtonElement = ocEl.querySelector(
      '.aui-confirm-dialog__cancel-button',
    );
    confirmBtn.dispatchEvent(new Event('click'));
    fixture.detectChanges();

    expect(confirmBtn.className).toContain('isLoading');
    expect(confirmBtn.disabled).toBeTruthy();
    expect(cancelBtn.disabled).toBeTruthy();

    tick(100);
    fixture.detectChanges();

    expect(ocEl.querySelector('aui-dialog')).not.toBeNull();
    expect(confirmBtn.className).not.toContain('isLoading');
    expect(confirmBtn.disabled).toBeFalsy();
    expect(cancelBtn.disabled).toBeFalsy();
  }));

  it('should open confirm dialog with templateRef content', () =>
    new Promise<void>(resolve => {
      const contentTemplateRefTestComponent = TestBed.createComponent(
        ContentTemplateRefTestComponent,
      );

      dialogService
        .confirm({
          title: 'title',
          content:
            contentTemplateRefTestComponent.componentInstance.templateRef,
        })
        .then(() => {
          expect(ocEl.querySelector('aui-dialog')).toBeNull();
          resolve();
        });
      fixture.detectChanges();
      expect(ocEl.querySelector('.content-template')).toBeTruthy();
      ocEl
        .querySelector('.aui-confirm-dialog__confirm-button')
        .dispatchEvent(new Event('click'));
    }));

  it('should open confirm dialog with component content', () =>
    new Promise<void>(resolve => {
      dialogService
        .confirm({
          title: 'title',
          content: ContentTemplateRefTestComponent,
        })
        .then(() => {
          expect(ocEl.querySelector('aui-dialog')).toBeNull();
          resolve();
        });
      fixture.detectChanges();
      expect(ocEl.querySelector('content-component')).toBeTruthy();
      ocEl
        .querySelector('.aui-confirm-dialog__confirm-button')
        .dispatchEvent(new Event('click'));
    }));
});
Example #20
Source File: multi-select.component.spec.ts    From alauda-ui with MIT License 4 votes vote down vote up
describe('multiSelectComponent', () => {
  let fixture: ComponentFixture<TestComponent>;
  let ins: TestComponent;
  let debugEl: DebugElement;
  let el: HTMLElement;
  let ocEl: HTMLElement;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [SelectModule, FormsModule],
      declarations: [TestComponent],
    });
    fixture = TestBed.createComponent(TestComponent);
    fixture.detectChanges();
    ins = fixture.componentInstance;
    debugEl = fixture.debugElement.query(By.css('.aui-multi-select'));
    el = debugEl.nativeElement;
    inject([OverlayContainer], (overlayContainer: OverlayContainer) => {
      ocEl = overlayContainer.getContainerElement();
    })();
  });

  it('should properties work correctly', fakeAsync(() => {
    expect(
      el.querySelector('.aui-multi-select__placeholder').innerHTML.trim(),
    ).toBe('');
    expect(el.className).not.toContain('isDisabled');
    expect(el.className).toContain('aui-multi-select--medium');
    ins.selectRef.contentOptions.forEach(option => {
      expect(option.size).toBe(ComponentSize.Medium);
    });
    ins.disabled = true;
    ins.loading = true;
    ins.clearable = true;
    ins.value = [1, 2];
    ins.size = ComponentSize.Large;
    ins.placeholder = 'placeholder';
    fixture.detectChanges();
    tick();
    expect(
      el.querySelector('.aui-multi-select__placeholder').innerHTML,
    ).toContain('placeholder');
    expect(el.className).toContain('isDisabled');
    expect(el.className).toContain('aui-multi-select--large');
    ins.selectRef.contentOptions.forEach(option => {
      expect(option.size).toBe(ComponentSize.Large);
    });
  }));

  it('should ngModel work', fakeAsync(() => {
    expect(el.querySelectorAll(':not(input).aui-tag').length).toBe(0);
    expect(
      ins.selectRef.contentOptions.filter(option => option.selected).length,
    ).toBe(0);
    ins.value = [1, 2];
    fixture.detectChanges();
    tick();
    expect(el.querySelectorAll(':not(input).aui-tag').length).toBe(2);
    expect(
      ins.selectRef.contentOptions.filter(option => option.selected).length,
    ).toBe(2);
    el.dispatchEvent(new Event('click'));
    fixture.detectChanges();
    ocEl
      .querySelectorAll('.aui-option')
      .item(2)
      .dispatchEvent(new Event('click'));
    fixture.detectChanges();
    expect(ins.value).toEqual([1, 2, 3]);
  }));

  it('should clearable work', fakeAsync(() => {
    ins.clearable = true;
    fixture.detectChanges();
    expect(el.querySelectorAll(':not(input).aui-tag').length).toBe(0);
    expect(
      ins.selectRef.contentOptions.filter(option => option.selected).length,
    ).toBe(0);
    ins.value = [1, 2];
    fixture.detectChanges();
    tick();
    expect(el.querySelectorAll(':not(input).aui-tag').length).toBe(2);
    expect(
      ins.selectRef.contentOptions.filter(option => option.selected).length,
    ).toBe(2);
    const closeEl = el.querySelector('.aui-multi-select__clear');
    closeEl.dispatchEvent(new Event('click'));
    fixture.detectChanges();
    expect(el.querySelectorAll(':not(input).aui-tag').length).toBe(0);
    expect(
      ins.selectRef.contentOptions.filter(option => option.selected).length,
    ).toBe(0);
    expect(ins.value).toEqual([]);
  }));

  it('should tagClassFn work', fakeAsync(() => {
    ins.value = [1, 2];
    fixture.detectChanges();
    tick();
    expect(el.querySelectorAll('.tag-1').length).toBe(1);
    expect(el.querySelectorAll('.tag-2').length).toBe(1);
  }));
});
Example #21
Source File: notification.service.spec.ts    From alauda-ui with MIT License 4 votes vote down vote up
describe('NotificationService', () => {
  let fixture: ComponentFixture<TestComponent>;
  let ocEl: HTMLElement;
  let notificationService: NotificationService;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [TestModule],
      providers: [
        {
          provide: NOTIFICATION_CONFIG,
          useValue: {
            duration: 3000,
            maxStack: 3,
          },
        },
      ],
    });

    fixture = TestBed.createComponent(TestComponent);

    inject(
      [OverlayContainer, NotificationService],
      (overlayContainer: OverlayContainer, service: NotificationService) => {
        ocEl = overlayContainer.getContainerElement();
        notificationService = service;
      },
    )();
  });

  it('should work with global config', () => {
    notificationService.success('notification success');
    fixture.detectChanges();
    expect(ocEl.querySelector('.aui-notification__close').innerHTML).toContain(
      '3s',
    );
    notificationService.success('notification success1');
    fixture.detectChanges();
    notificationService.success('notification success2');
    fixture.detectChanges();
    notificationService.success('notification success3');
    fixture.detectChanges();
    notificationService.success('notification success4');
    fixture.detectChanges();
    notificationService.success('notification success5');
    fixture.detectChanges();
    expect(ocEl.querySelectorAll('.aui-notification').length).toEqual(6);
  });

  it('should show a success notification with  string', () => {
    notificationService.success('notification success');
    fixture.detectChanges();
    expect(ocEl.querySelector('.aui-notification')).not.toBeNull();
    expect(ocEl.querySelector('.aui-notification').classList).toContain(
      'aui-notification--success',
    );
    expect(
      ocEl.querySelector('.aui-notification__content').textContent,
    ).toContain('notification success');
  });

  it('should show a success notification with object', () => {
    notificationService.success({
      content: 'notification success object',
    });
    fixture.detectChanges();
    expect(ocEl.querySelector('.aui-notification')).not.toBeNull();
    expect(ocEl.querySelector('.aui-notification').classList).toContain(
      'aui-notification--success',
    );
    expect(
      ocEl.querySelector('.aui-notification__content').innerHTML,
    ).toContain('notification success object');
  });

  it('should show a success notification with template', () => {
    notificationService.success({
      contentRef: fixture.componentInstance.templateRef,
      duration: 10_000,
    });
    fixture.detectChanges();

    expect(ocEl.querySelector('.aui-notification button')).not.toBeNull();
    expect(ocEl.querySelector('.aui-notification button').classList).toContain(
      'temp-btn',
    );
    expect(ocEl.querySelector('.aui-notification__close').innerHTML).toContain(
      '10s',
    );
  });

  it('should show a success notification with component', () => {
    notificationService.success({
      contentRef: NotificationContentComponent,
    });
    fixture.detectChanges();

    expect(
      ocEl.querySelector('.aui-notification .notification-demo-content'),
    ).not.toBeNull();
    expect(
      ocEl.querySelector('.aui-notification .notification-demo-content')
        .innerHTML,
    ).toContain('demo content');
  });
});
Example #22
Source File: angular-context.spec.ts    From s-libs with MIT License 4 votes vote down vote up
describe('AngularContext', () => {
  class SnackBarContext extends AngularContext {
    constructor() {
      super({ imports: [MatSnackBarModule, NoopAnimationsModule] });
    }

    protected override cleanUp(): void {
      this.inject(OverlayContainer).ngOnDestroy();
      flush();
      super.cleanUp();
    }
  }

  describe('.getCurrent()', () => {
    it('returns the currently running angular context', () => {
      expect(AngularContext.getCurrent()).toBeUndefined();

      const ctx = new AngularContext();
      ctx.run(() => {
        expect(AngularContext.getCurrent()).toBe(ctx);
      });

      expect(AngularContext.getCurrent()).toBeUndefined();
    });
  });

  describe('.startTime', () => {
    it('controls the time at which the test starts', () => {
      const ctx = new AngularContext();
      ctx.startTime = new Date('2012-07-14T21:42:17.523Z');
      ctx.run(() => {
        expect(new Date()).toEqual(new Date('2012-07-14T21:42:17.523Z'));
      });
    });

    it('defaults to the current time', () => {
      const ctx = new AngularContext();
      const now = Date.now();
      ctx.run(() => {
        expect(Date.now()).toBeCloseTo(now, -1);
      });
    });
  });

  describe('constructor', () => {
    it('accepts module metadata to be bootstrapped', () => {
      const value = Symbol();
      const token = new InjectionToken<symbol>('tok');
      const ctx = new AngularContext({
        providers: [{ provide: token, useValue: value }],
      });
      ctx.run(() => {
        expect(ctx.inject(token)).toBe(value);
      });
    });

    it('sets up HttpClientTestingModule', () => {
      const ctx = new AngularContext();
      ctx.run(() => {
        expect(ctx.inject(HttpTestingController)).toBeDefined();
      });
    });

    it('sets up MockErrorHandler', () => {
      const ctx = new AngularContext();
      ctx.run(() => {
        expect(ctx.inject(ErrorHandler)).toEqual(jasmine.any(MockErrorHandler));
      });
    });

    it('gives a nice error message if trying to use 2 at the same time', () => {
      new AngularContext().run(async () => {
        expect(() => {
          // eslint-disable-next-line no-new -- nothing more is needed for this test
          new AngularContext();
        }).toThrowError(
          'There is already another AngularContext in use (or it was not cleaned up)',
        );
      });
    });
  });

  describe('.run()', () => {
    it('uses the fakeAsync zone', () => {
      const ctx = new AngularContext();
      ctx.run(() => {
        expect(tick).not.toThrow();
      });
    });

    it('can handle async tests that call tick', () => {
      let completed = false;
      const ctx = new AngularContext();
      ctx.run(async () => {
        await sleep(0);
        setTimeout(() => {
          completed = true;
        }, 500);
        ctx.tick(500);
      });
      expect(completed).toBeTrue();
    });

    it('does not swallow errors (production bug)', () => {
      expect(() => {
        new AngularContext().run(() => {
          throw new Error();
        });
      }).toThrowError();
    });
  });

  describe('.inject()', () => {
    it('fetches from the root injector', () => {
      const ctx = new AngularContext();
      ctx.run(() => {
        expect(ctx.inject(Injector)).toBe(TestBed.inject(Injector));
      });
    });
  });

  describe('.hasHarness()', () => {
    it('returns whether a match for the harness exists', () => {
      const ctx = new SnackBarContext();
      ctx.run(async () => {
        expect(await ctx.hasHarness(MatSnackBarHarness)).toBe(false);

        ctx.inject(MatSnackBar).open('hi');
        expect(await ctx.hasHarness(MatSnackBarHarness)).toBe(true);
      });
    });
  });

  describe('.getHarness()', () => {
    it('returns a harness', () => {
      const ctx = new SnackBarContext();
      ctx.run(async () => {
        ctx.inject(MatSnackBar).open('hi');
        const bar = await ctx.getHarness(MatSnackBarHarness);
        expect(await bar.getMessage()).toBe('hi');
      });
    });
  });

  describe('.getAllHarnesses()', () => {
    it('gets an array of harnesses', () => {
      const ctx = new SnackBarContext();
      ctx.run(async () => {
        let bars = await ctx.getAllHarnesses(MatSnackBarHarness);
        expect(bars.length).toBe(0);
        ctx.inject(MatSnackBar).open('hi');
        bars = await ctx.getAllHarnesses(MatSnackBarHarness);
        expect(bars.length).toBe(1);
        expect(await bars[0].getMessage()).toBe('hi');
      });
    });
  });

  describe('.tick()', () => {
    it('defaults to not advance time', () => {
      const ctx = new AngularContext();
      const start = ctx.startTime.getTime();
      ctx.run(() => {
        ctx.tick();
        expect(Date.now()).toBe(start);
      });
    });

    it('defaults to advancing in milliseconds', () => {
      const ctx = new AngularContext();
      const start = ctx.startTime.getTime();
      ctx.run(() => {
        ctx.tick(10);
        expect(Date.now()).toBe(start + 10);
      });
    });

    it('allows specifying the units to advance', () => {
      const ctx = new AngularContext();
      const start = ctx.startTime.getTime();
      ctx.run(() => {
        ctx.tick(10, 'sec');
        expect(Date.now()).toBe(start + 10000);
      });
    });

    it('runs change detection even if no tasks are queued', () => {
      let ranChangeDetection = false;

      @Component({ template: '' })
      class LocalComponent implements DoCheck {
        ngDoCheck(): void {
          ranChangeDetection = true;
        }
      }
      TestBed.overrideComponent(LocalComponent, {});

      const ctx = new AngularContext();
      ctx.run(() => {
        const resolver = ctx.inject(ComponentFactoryResolver);
        const factory = resolver.resolveComponentFactory(LocalComponent);
        const componentRef = factory.create(ctx.inject(Injector));
        ctx.inject(ApplicationRef).attachView(componentRef.hostView);

        expect(ranChangeDetection).toBe(false);
        ctx.tick();
        expect(ranChangeDetection).toBe(true);
      });
    });

    it('flushes micro tasks before running change detection', () => {
      let ranChangeDetection = false;
      let flushedMicroTasksBeforeChangeDetection = false;

      @Component({ template: '' })
      class LocalComponent implements DoCheck {
        ngDoCheck(): void {
          ranChangeDetection = true;
        }
      }
      TestBed.overrideComponent(LocalComponent, {});

      const ctx = new AngularContext();
      ctx.run(() => {
        const resolver = ctx.inject(ComponentFactoryResolver);
        const factory = resolver.resolveComponentFactory(LocalComponent);
        const componentRef = factory.create(ctx.inject(Injector));
        ctx.inject(ApplicationRef).attachView(componentRef.hostView);

        Promise.resolve().then(() => {
          flushedMicroTasksBeforeChangeDetection = !ranChangeDetection;
        });
        ctx.tick();
        expect(flushedMicroTasksBeforeChangeDetection).toBe(true);
      });
    });

    it('runs change detection after timeouts', () => {
      let ranTimeout = false;
      let ranChangeDetectionAfterTimeout = false;

      @Component({ template: '' })
      class LocalComponent implements DoCheck {
        ngDoCheck(): void {
          ranChangeDetectionAfterTimeout = ranTimeout;
        }
      }
      TestBed.overrideComponent(LocalComponent, {});

      const ctx = new AngularContext();
      ctx.run(() => {
        const resolver = ctx.inject(ComponentFactoryResolver);
        const factory = resolver.resolveComponentFactory(LocalComponent);
        const componentRef = factory.create(ctx.inject(Injector));
        ctx.inject(ApplicationRef).attachView(componentRef.hostView);

        setTimeout(() => {
          ranTimeout = true;
        });
        ctx.tick();
        expect(ranChangeDetectionAfterTimeout).toBe(true);
      });
    });

    it('advances `performance.now()`', () => {
      const ctx = new AngularContext();
      ctx.run(() => {
        const start = performance.now();
        ctx.tick(10);
        expect(performance.now()).toBe(start + 10);
      });
    });

    it('gives a nice error message when you try to use it outside `run()`', () => {
      const ctx = new AngularContext();
      expect(() => {
        ctx.tick();
      }).toThrowError(
        '.tick() only works inside the .run() callback (because it needs to be in a fakeAsync zone)',
      );
      ctx.run(noop);
    });
  });

  describe('.verifyPostTestConditions()', () => {
    it('errs if there are unexpected http requests', () => {
      const ctx = new AngularContext();
      expect(() => {
        ctx.run(() => {
          ctx.inject(HttpClient).get('an unexpected URL').subscribe();
        });
      }).toThrowError(
        'Expected no open requests, found 1: GET an unexpected URL',
      );
    });

    it('errs if there are unexpected errors', () => {
      @Component({ template: '<button (click)="throwError()"></button>' })
      class ThrowingComponent {
        throwError(): never {
          throw new Error();
        }
      }

      const ctx = new ComponentContext(ThrowingComponent);
      expect(() => {
        ctx.run(async () => {
          // TODO: make something like `ctx.getTestElement()`?
          const loader = FakeAsyncHarnessEnvironment.documentRootLoader(ctx);
          const button = await loader.locatorFor('button')();
          await button.click();
        });
      }).toThrowError('Expected no error(s), found 1');
    });
  });

  describe('.cleanUp()', () => {
    it('discards periodic tasks', () => {
      const ctx = new AngularContext();
      expect(() => {
        ctx.run(() => {
          setInterval(noop, 10);
        });
      })
        // No error: "1 periodic timer(s) still in the queue."
        .not.toThrowError();
    });

    it('flushes pending timeouts', () => {
      const ctx = new AngularContext();
      expect(() => {
        ctx.run(() => {
          setTimeout(noop, 1);
        });
      })
        // No error: "1 timer(s) still in the queue."
        .not.toThrowError();
    });
  });
});
Example #23
Source File: tree-select.component.spec.ts    From alauda-ui with MIT License 4 votes vote down vote up
describe('TreeSelectComponent', () => {
  let fixture: ComponentFixture<TestComponent>;
  let ins: TestComponent;
  let debugEl: DebugElement;
  let el: HTMLElement;
  let inputEl: HTMLInputElement;
  let ocEl: HTMLElement;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [TreeSelectModule, FormsModule],
      declarations: [TestComponent],
    });
    fixture = TestBed.createComponent(TestComponent);
    fixture.detectChanges();
    ins = fixture.componentInstance;
    debugEl = fixture.debugElement.query(By.css('.aui-tree-select'));
    el = debugEl.nativeElement;
    inputEl = debugEl.query(By.css('.aui-input')).nativeElement;

    inject([OverlayContainer], (overlayContainer: OverlayContainer) => {
      ocEl = overlayContainer.getContainerElement();
    })();
  });

  it('should properties work correctly', () => {
    expect(inputEl.placeholder).toBe('');
    expect(inputEl.disabled).toBeFalsy();

    ins.disabled = true;
    ins.loading = true;
    ins.clearable = true;
    ins.placeholder = 'placeholder';
    fixture.detectChanges();

    expect(inputEl.placeholder).toBe('placeholder');
    expect(inputEl.disabled).toBeTruthy();
    expect(
      el
        .querySelector('.aui-tree-select__indicator .aui-icon')
        .getAttribute('class'),
    ).toContain('aui-icon-spinner');
  });

  it('should ngModel work', fakeAsync(() => {
    ins.selectRef.openNodes();
    fixture.detectChanges();

    expect(
      ocEl.querySelector('.aui-tree-node[data-value=a-1]').className,
    ).toContain('isSelected');
    expect(inputEl.value).toBe('a-1');

    ins.value = 'b-2';
    fixture.detectChanges();
    tick();
    expect(inputEl.value).toBe('b-2');
    ins.selectRef.openNodes();
    fixture.detectChanges();
    expect(
      ocEl.querySelector('.aui-tree-node[data-value=b-2]').className,
    ).toContain('isSelected');

    ocEl
      .querySelector('.aui-tree-node[data-value=a-4-1] .aui-tree-node__title')
      .dispatchEvent(new Event('click'));
    fixture.detectChanges();
    expect(ins.value).toBe('a-4-1');
    expect(ins.selectRef.displayText).toBe('a-4-1');
  }));

  it('should clearable work', () => {
    ins.clearable = true;
    fixture.detectChanges();
    const closeEl = el.querySelector('.aui-tree-select__clear');
    expect(closeEl).not.toBeNull();
    closeEl.dispatchEvent(new Event('click'));
    fixture.detectChanges();
    expect(ins.value).toBe(null);
    expect(inputEl.value).toBe('');
  });

  it('should tree node could be disabled', () => {
    ins.selectRef.openNodes();
    fixture.detectChanges();
    ocEl
      .querySelector('.aui-tree-node[data-value=a-3] .aui-tree-node__title')
      .dispatchEvent(new Event('click'));
    fixture.detectChanges();
    expect(inputEl.value).toBe('a-1');
  });
});
Example #24
Source File: tooltip.directive.spec.ts    From alauda-ui with MIT License 4 votes vote down vote up
describe('TooltipDirective', () => {
  let fixture: ComponentFixture<TestComponent>;
  let ins: TestComponent;
  let debugEl: DebugElement;
  let hostEl: HTMLElement;
  let ocEl: HTMLElement;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [TooltipModule, FormsModule],
      declarations: [TestComponent],
    });
    fixture = TestBed.createComponent(TestComponent);
    fixture.detectChanges();
    ins = fixture.componentInstance;
    debugEl = fixture.debugElement.query(By.css('#host'));
    hostEl = debugEl.nativeElement;

    inject([OverlayContainer], (overlayContainer: OverlayContainer) => {
      ocEl = overlayContainer.getContainerElement();
    })();
  });

  it('should render tooltip when mouseenter & destroy tooltip when mouseleave', fakeAsync(() => {
    hostEl.dispatchEvent(new Event('mouseenter'));
    tick(DISPLAY_DELAY);
    fixture.detectChanges();

    expect(ins.tooltip.isCreated).toBeTruthy();
    expect(ocEl.querySelector('.aui-tooltip').innerHTML).toContain(
      'hello world',
    );
    expect(hostEl.className).toContain('tooltip-actived');

    hostEl.dispatchEvent(new Event('mouseleave'));
    tick(HIDDEN_DELAY);

    expect(ins.tooltip.isCreated).toBeFalsy();
    expect(ocEl.querySelector('.aui-tooltip')).toBeNull();
    expect(hostEl.className).not.toContain('tooltip-actived');
  }));

  it('should still display when mouse move to tooltip', fakeAsync(() => {
    hostEl.dispatchEvent(new Event('mouseenter'));
    tick(DISPLAY_DELAY);
    fixture.detectChanges();
    hostEl.dispatchEvent(new Event('mouseleave'));
    tick(20);
    ocEl.querySelector('.aui-tooltip').dispatchEvent(new Event('mouseenter'));
    tick(20);
    fixture.detectChanges();

    expect(ins.tooltip.isCreated).toBeTruthy();
    expect(ocEl.querySelector('.aui-tooltip')).not.toBeNull();
    tick(HIDDEN_DELAY - 40);
  }));

  it('should click trigger work', () => {
    ins.trigger = TooltipTrigger.Click;
    fixture.detectChanges();
    hostEl.dispatchEvent(new Event('click'));
    fixture.detectChanges();
    expect(ocEl.querySelector('.aui-tooltip')).not.toBeNull();
    document.body.click();
    expect(ocEl.querySelector('.aui-tooltip')).toBeNull();

    hostEl.dispatchEvent(new Event('click'));
    fixture.detectChanges();
    expect(ocEl.querySelector('.aui-tooltip')).not.toBeNull();
    hostEl.dispatchEvent(new Event('click'));
    expect(ocEl.querySelector('.aui-tooltip')).toBeNull();
  });

  it('should focus trigger work', () => {
    ins.trigger = TooltipTrigger.Focus;
    fixture.detectChanges();
    hostEl.dispatchEvent(new Event('focus'));
    fixture.detectChanges();

    expect(ocEl.querySelector('.aui-tooltip')).not.toBeNull();

    hostEl.dispatchEvent(new Event('blur'));

    expect(ocEl.querySelector('.aui-tooltip')).toBeNull();
  });

  it('should can be disabled', () => {
    ins.disabled = true;
    ins.trigger = TooltipTrigger.Click;
    fixture.detectChanges();
    hostEl.dispatchEvent(new Event('click'));
    fixture.detectChanges();

    expect(ocEl.querySelector('.aui-tooltip')).toBeNull();
  });

  it('should tooltip configs work', () => {
    ins.trigger = TooltipTrigger.Click;
    ins.content = 'custom content';
    ins.type = TooltipType.Primary;
    ins.position = 'start';
    ins.className = 'custom-class';
    fixture.detectChanges();
    hostEl.dispatchEvent(new Event('click'));
    fixture.detectChanges();

    const tooltipEl = ocEl.querySelector('.aui-tooltip');
    expect(tooltipEl.innerHTML).toContain('custom content');
    expect(tooltipEl.className).toContain('aui-tooltip--primary');
    expect(tooltipEl.className).toContain('aui-tooltip--start');
    expect(tooltipEl.className).toContain('custom-class');
  });

  it('should tooltip render templateRef', () => {
    ins.trigger = TooltipTrigger.Click;
    ins.content = ins.templateRef;
    ins.context = { text: 'custom context' };
    fixture.detectChanges();
    hostEl.dispatchEvent(new Event('click'));
    fixture.detectChanges();

    expect(ocEl.querySelector('#dataNode').innerHTML).toContain(
      'custom context',
    );
  });

  it('should emit show event', () =>
    new Promise(resolve => {
      ins.tooltip.show.subscribe(resolve);

      ins.trigger = TooltipTrigger.Click;
      fixture.detectChanges();
      hostEl.dispatchEvent(new Event('click'));
      fixture.detectChanges();
    }));

  it('should emit hide event', () =>
    new Promise(resolve => {
      ins.tooltip.hide.subscribe(resolve);

      ins.trigger = TooltipTrigger.Click;
      fixture.detectChanges();
      hostEl.dispatchEvent(new Event('click'));
      document.body.click();
    }));
});
Example #25
Source File: app.component.spec.ts    From WowUp with GNU General Public License v3.0 4 votes vote down vote up
describe("AppComponent", () => {
  let addonServiceSpy: AddonService;
  let electronServiceSpy: ElectronService;
  let wowUpServiceSpy: WowUpService;
  let sessionServiceSpy: SessionService;
  let fileServiceSpy: FileService;
  let analyticsServiceSpy: AnalyticsService;
  let preferenceStorageSpy: PreferenceStorageService;
  let wowUpAddonServiceSpy: WowUpAddonService;
  let warcraftInstallationService: WarcraftInstallationService;
  let zoomService: ZoomService;
  let addonProviderService: any;

  beforeEach(async () => {
    wowUpAddonServiceSpy = jasmine.createSpyObj(
      "WowUpAddonService",
      ["updateForClientType", "updateForAllClientTypes"],
      {
        persistUpdateInformationToWowUpAddon: () => {},
      }
    );

    addonServiceSpy = jasmine.createSpyObj("AddonService", ["processAutoUpdates", "syncAllClients"], {
      syncError$: new Subject(),
    });

    addonProviderService = jasmine.createSpyObj(
      "AddonProviderFactory",
      {
        getAdRequiredProviders: () => [],
      },
      {}
    );

    warcraftInstallationService = jasmine.createSpyObj("WarcraftInstallationService", [""], {
      wowInstallations$: new Subject(),
    });

    zoomService = jasmine.createSpyObj("ZoomService", [""], {});

    electronServiceSpy = jasmine.createSpyObj("ElectronService", ["invoke", "on", "off"], {
      appOptions: { quit: null },
      getAppOptions: () => Promise.resolve({}),
      powerMonitor$: new Observable(),
      appUpdate$: new Observable(),
      ipcRenderer: {
        on: () => {},
      },
    });
    wowUpServiceSpy = jasmine.createSpyObj("WowUpService", [""], {
      preferenceChange$: new Subject<PreferenceChange>().asObservable(),
    });
    sessionServiceSpy = jasmine.createSpyObj("SessionService", ["autoUpdateComplete"], {
      adSpace$: new BehaviorSubject(false),
    });
    fileServiceSpy = jasmine.createSpyObj("FileService", [""]);
    analyticsServiceSpy = jasmine.createSpyObj("AnalyticsService", ["trackStartup"]);
    preferenceStorageSpy = jasmine.createSpyObj("PreferenceStorageService", ["get"], {});

    await TestBed.configureTestingModule({
      declarations: [AppComponent, AnimatedLogoComponent],
      providers: [MatDialog, ElectronService],
      imports: [
        OverlayModule,
        RouterTestingModule,
        HttpClientModule,
        MatModule,
        NoopAnimationsModule,
        TranslateModule.forRoot({
          loader: {
            provide: TranslateLoader,
            useFactory: httpLoaderFactory,
            deps: [HttpClient],
          },
          compiler: {
            provide: TranslateCompiler,
            useClass: TranslateMessageFormatCompiler,
          },
        }),
      ],
    })
      .overrideComponent(AppComponent, {
        set: {
          providers: [
            MatDialog,
            OverlayContainer,
            { provide: AddonService, useValue: addonServiceSpy },
            { provide: ElectronService, useValue: electronServiceSpy },
            { provide: WowUpService, useValue: wowUpServiceSpy },
            { provide: SessionService, useValue: sessionServiceSpy },
            { provide: FileService, useValue: fileServiceSpy },
            { provide: AnalyticsService, useValue: analyticsServiceSpy },
            { provide: PreferenceStorageService, useValue: preferenceStorageSpy },
            { provide: WowUpAddonService, useValue: wowUpAddonServiceSpy },
            { provide: WarcraftInstallationService, useValue: warcraftInstallationService },
            { provide: ZoomService, useValue: zoomService },
            { provide: AddonProviderFactory, useValue: addonProviderService },
          ],
        },
      })
      .compileComponents();
  });

  it("should create", () => {
    const fixture = TestBed.createComponent(AppComponent);
    expect(fixture.componentInstance).toBeTruthy();
  });
});
Example #26
Source File: select.component.spec.ts    From alauda-ui with MIT License 4 votes vote down vote up
describe('SelectComponent', () => {
  let fixture: ComponentFixture<TestComponent>;
  let ins: TestComponent;
  let debugEl: DebugElement;
  let el: HTMLElement;
  let inputEl: HTMLInputElement;
  let ocEl: HTMLElement;
  let getLabelEl: () => HTMLElement;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [SelectModule, FormsModule],
      declarations: [TestComponent],
    });
    fixture = TestBed.createComponent(TestComponent);
    fixture.detectChanges();
    ins = fixture.componentInstance;
    debugEl = fixture.debugElement.query(By.css('.aui-select'));
    el = debugEl.nativeElement;
    inputEl = debugEl.query(By.css('input.aui-input'))
      .nativeElement as HTMLInputElement;
    getLabelEl = () => el.querySelector('.aui-select__label');

    inject([OverlayContainer], (overlayContainer: OverlayContainer) => {
      ocEl = overlayContainer.getContainerElement();
    })();
  });

  it('should properties work correctly', () => {
    expect(inputEl.placeholder).toBe('');
    expect(inputEl.disabled).toBeFalsy();
    expect(inputEl.className).toContain('aui-input--medium');
    ins.selectRef.contentOptions.forEach(option => {
      expect(option.size).toBe(ComponentSize.Medium);
    });

    ins.disabled = true;
    ins.loading = true;
    ins.clearable = true;
    ins.size = ComponentSize.Large;
    fixture.detectChanges();

    expect(inputEl.disabled).toBeTruthy();
    expect(inputEl.className).toContain('aui-input--large');
    ins.selectRef.contentOptions.forEach(option => {
      expect(option.size).toBe(ComponentSize.Large);
    });
  });

  it('should [(value)] work', () => {
    el.dispatchEvent(new Event('click'));
    fixture.detectChanges();

    const optionEls = ocEl.querySelectorAll('.aui-option');
    expect(optionEls.item(0).className).toContain('isSelected');
    expect(getLabelEl().innerHTML).toContain('1');
    ins.value = {
      label: '5',
      value: 5,
    };
    fixture.detectChanges();
    expect(getLabelEl().innerHTML).toContain('5');

    ins.value = {
      label: '0',
      value: Symbol(0),
    };
    fixture.detectChanges();
    expect(getLabelEl().innerHTML).toContain('0');

    optionEls.item(1).dispatchEvent(new Event('click'));
    fixture.detectChanges();
    expect(ins.value.value).toBe(2);
    expect(getLabelEl().innerHTML).toContain('2');
  });

  it('should clearable work', () => {
    ins.clearable = true;
    fixture.detectChanges();

    expect(ins.value.value).toBe(1);
    expect(getLabelEl().innerHTML).toContain('1');

    const closeEl = el.querySelector('.aui-select__clear');
    closeEl.dispatchEvent(new Event('click'));
    fixture.detectChanges();

    expect(ins.value).toBe(null);
    expect(getLabelEl().textContent).toEqual('');
  });

  it('should label correctly rendered', () => {
    ins.getOptionLabel = (label: string) => `custom label for ${label}`;
    expect(getLabelEl().innerHTML).toContain('1');
    fixture.detectChanges();
    expect(getLabelEl().innerHTML).toContain('custom label for 1');
    ins.getOptionLabel = (label: string) => `new custom label for ${label}`;
    fixture.detectChanges();
    expect(getLabelEl().innerHTML).toContain('new custom label for 1');
  });
});