@angular/core/testing#fakeAsync TypeScript Examples

The following examples show how to use @angular/core/testing#fakeAsync. 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: sleep.spec.ts    From s-libs with MIT License 6 votes vote down vote up
describe('sleep()', () => {
  it('resolves after the given delay', fakeAsync(() => {
    let resolved = false;
    sleep(1000).then(() => {
      resolved = true;
    });

    tick(999);
    expect(resolved).toBe(false);
    tick(1);
    expect(resolved).toBe(true);
  }));
});
Example #2
Source File: analytics.spec.ts    From frontend-frameworks with MIT License 6 votes vote down vote up
describe('analytics', () => {
  let component: CloudinaryImageComponent;
  let fixture: ComponentFixture<CloudinaryImageComponent>;

  beforeEach(() => {
    SDKAnalyticsConstants.sdkSemver = '1.0.0';
    SDKAnalyticsConstants.techVersion = '10.2.5';
    TestBed.configureTestingModule({
      declarations: [ CloudinaryImageComponent ],
    });
    fixture = TestBed.createComponent(CloudinaryImageComponent);
    component = fixture.componentInstance;
  });

  afterEach(() => {
    SDKAnalyticsConstants.sdkSemver = APP_VERSION;
    SDKAnalyticsConstants.techVersion = VERSION.full;
  });

  it('creates an img with analytics', fakeAsync(() => {
    component.cldImg = cloudinaryImage;
    fixture.detectChanges();
    tick(0);
    const imgElement: HTMLImageElement = fixture.nativeElement;
    const img = imgElement.querySelector('img');

    expect(img.src).toBe('https://res.cloudinary.com/demo/image/upload/sample?_a=AKAABDS0');
  }));
});
Example #3
Source File: delay-on-microtask-queue.spec.ts    From s-libs with MIT License 6 votes vote down vote up
describe('delayOnMicrotaskQueue()', () => {
  it('passes along values asynchronously', fakeAsync(() => {
    const source = new Subject<number>();
    const spy = jasmine.createSpy();
    source.pipe(delayOnMicrotaskQueue()).subscribe(spy);

    source.next(1);
    expect(spy).not.toHaveBeenCalled();
    flushMicrotasks();
    expectSingleCallAndReset(spy, 1);

    source.next(2);
    expect(spy).not.toHaveBeenCalled();
    flushMicrotasks();
    expectSingleCallAndReset(spy, 2);
  }));

  it(
    'passes along unsubscribes synchronously',
    testUnsubscribePropagation(delayOnMicrotaskQueue),
  );

  it(
    'passes along errors synchronously',
    testErrorPropagation(delayOnMicrotaskQueue),
  );

  it(
    'passes along completion synchronously',
    testCompletionPropagation(delayOnMicrotaskQueue),
  );
});
Example #4
Source File: lazyload.spec.ts    From frontend-frameworks with MIT License 6 votes vote down vote up
describe('lazyload', () => {
  let component: CloudinaryImageComponent;
  let fixture: ComponentFixture<CloudinaryImageComponent>;

  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [ CloudinaryImageComponent ],
    });
    fixture = TestBed.createComponent(CloudinaryImageComponent);
    component = fixture.componentInstance;
  });

  it('should not have src pre-scroll', fakeAsync(() => {
    component.cldImg = cloudinaryImage;
    component.plugins = [lazyload()];
    fixture.detectChanges();

    const divElement = document.createElement('div');
    divElement.style.height = '3000px';
    fixture.nativeElement.insertBefore(divElement, fixture.nativeElement.firstChild);

    tick(0);

    const imgElement: HTMLImageElement = fixture.nativeElement;
    const img = imgElement.querySelector('img');
    expect(img.src).toBe( '');
  }));
});
Example #5
Source File: home.component.spec.ts    From Angular-Cookbook with MIT License 6 votes vote down vote up
describe('HomeComponent', () => {
  let component: HomeComponent;
  let fixture: ComponentFixture<HomeComponent>;

  beforeEach(
    waitForAsync(() => {
      TestBed.configureTestingModule({
        declarations: [HomeComponent],
        imports: [HttpClientModule],
      }).compileComponents();
    })
  );

  beforeEach(() => {
    fixture = TestBed.createComponent(HomeComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });

  it('should not send an http request before the debounceTime of 300ms', fakeAsync(async () => {
    spyOn(component, 'searchUsers');
    component.searchForm.get('username').setValue('iri');
    tick(component.searchDebounceTime - 10); // less than desired debounce time
    expect(component.searchUsers).not.toHaveBeenCalled();
    discardPeriodicTasks();
  }));

  it('should send an http request after the debounceTime of 300ms', fakeAsync(async () => {
    spyOn(component, 'searchUsers');
    component.searchForm.get('username').setValue('iri');
    tick(component.searchDebounceTime + 10); // more than desired debounce time
    expect(component.searchUsers).toHaveBeenCalled();
    discardPeriodicTasks();
  }));
});
Example #6
Source File: block-card.component.spec.ts    From slate-angular with MIT License 6 votes vote down vote up
describe('Block Card Component', () => {
    let component: ImageEditableComponent;
    let fixture: ComponentFixture<ImageEditableComponent>;

    beforeEach(fakeAsync(() => {
        configureBasicEditableTestingModule([ImageEditableComponent]);
        fixture = TestBed.createComponent(ImageEditableComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
        flush();
        fixture.detectChanges();
    }));    

    it('The block-card component should be created', fakeAsync(() => {
        let blockCardElement: HTMLElement;
        blockCardElement = fixture.debugElement.query(By.css('.slate-block-card')).nativeElement;
        expect(blockCardElement).toBeTruthy();
    }));
});
Example #7
Source File: ngx-tippy-group.spec.ts    From ngx-tippy-wrapper with MIT License 6 votes vote down vote up
describe('Component: NgxTippyGroupComponent (wrapped)', () => {
  let injector: TestBed;
  let fixture: ComponentFixture<TestWrapperComponent>;
  let component: TestWrapperComponent;
  let debugEl: DebugElement;

  beforeEach(async () => {
    TestBed.configureTestingModule({
      declarations: [NgxTippyGroupComponent, TestWrapperComponent],
      providers: [
        {
          provide: NGX_TIPPY_MESSAGES,
          useValue: messagesDict,
        },
      ],
    })
      .compileComponents()
      .then(() => {
        injector = getTestBed();
        fixture = injector.createComponent(TestWrapperComponent);
        component = fixture.componentInstance;
        debugEl = fixture.debugElement;
        fixture.detectChanges();
      });
  });

  it('should create wrapper test component', () => {
    expect(component).toBeTruthy();
  });

  it('should render all grouped elements', () => {
    const groupEls = debugEl.queryAll(By.css('button[data-tippy-grouped]'));

    expect(groupEls).toBeTruthy();
    expect(groupEls.length).toBe(3);
  });

  it('should show tooltips on click', () => {
    const groupEls = debugEl.queryAll(By.css('button[data-tippy-grouped]'));
    groupEls.forEach(el => {
      el.nativeElement.dispatchEvent(new MouseEvent('click'));
    });
    fixture.detectChanges();
    const tooltips = fixture.debugElement.queryAll(By.css('div[data-tippy-root]'));

    expect(tooltips).toBeTruthy();
    expect(tooltips.length).toBe(3);
  });

  it('should apply properties', fakeAsync(() => {
    const groupEls = debugEl.queryAll(By.css('button[data-tippy-grouped]'));
    groupEls.forEach(el => {
      el.nativeElement.dispatchEvent(new MouseEvent('click'));
    });
    fixture.detectChanges();

    const tooltipArrow = fixture.debugElement.queryAll(By.css('.tippy-arrow'));
    const tippyBox = fixture.debugElement.queryAll(By.css('.tippy-box'));
    const tooltipBgColor = getComputedStyle(tippyBox[1].nativeElement).backgroundColor;

    expect(tooltipArrow[0]).toBeUndefined();
    expect(tooltipBgColor).toBe('rgb(255, 255, 255)');

    let dataPlacement!: string;
    setTimeout(() => {
      dataPlacement = tippyBox[2].nativeElement.dataset.placement;
    }, 0);

    tick(0);

    expect(dataPlacement).toBe('bottom');
  }));
});
Example #8
Source File: autofocus.directive.spec.ts    From jira-clone-angular with MIT License 6 votes vote down vote up
describe('AutofocusDirective', () => {
  let component: any;
  const elementRef: any = {
    nativeElement: {
      focus: jasmine.createSpy('nativeElement')
    }
  };

  beforeEach(() => {
    component = new AutofocusDirective(
      elementRef
    );
  });

  it('should be able to make ng After Content Init', fakeAsync(() => {
    component.ngAfterContentInit();
    tick(10);
    expect(component.enable).toBe(true);
    expect(elementRef.nativeElement.focus).toHaveBeenCalled();
  }));
  it('should be able to make ng After Content Init and destroy', fakeAsync(() => {
    component.ngAfterContentInit();
    tick(10);
    component.ngOnDestroy();
    expect(component.timer).toEqual(null);
  }));
});
Example #9
Source File: loader.component.spec.ts    From one-platform with MIT License 6 votes vote down vote up
describe('LoaderComponent', () => {
  let component: LoaderComponent;
  let fixture: ComponentFixture<LoaderComponent>;
  const mockTitle = 'loading';

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [LoaderComponent],
    }).compileComponents();
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(LoaderComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });

  it('should have title', fakeAsync(() => {
    component.title = mockTitle;
    tick();
    fixture.detectChanges();
    const el: HTMLElement = fixture.nativeElement;
    expect(el.textContent).toContain(mockTitle);
  }));
});
Example #10
Source File: ngx-mat-autofocus.directive.spec.ts    From ngx-mat-timepicker with MIT License 6 votes vote down vote up
describe("AutofocusDirective", () => {
    let component: TestComponent;
    let fixture: ComponentFixture<TestComponent>;
    let debugElement: DebugElement;
    let directive: NgxMatTimepickerAutofocusDirective;

    beforeEach(() => {
        fixture = TestBed.configureTestingModule({
            declarations: [TestComponent, NgxMatTimepickerAutofocusDirective],
            schemas: [NO_ERRORS_SCHEMA]
        }).createComponent(TestComponent);

        component = fixture.componentInstance;
        debugElement = fixture.debugElement.query(By.directive(NgxMatTimepickerAutofocusDirective));
        directive = debugElement.injector.get(NgxMatTimepickerAutofocusDirective);
        fixture.detectChanges();
    });

    it("should focus element on which directive is applied", fakeAsync(() => {
        expect(document.activeElement).toEqual(document.body);
        directive.ngOnChanges();
        tick();
        expect(document.activeElement).toEqual(debugElement.nativeElement);
    }));

    it("should not focus element on which directive is applied", fakeAsync(() => {
        directive.isFocusActive = false;
        expect(document.activeElement).toEqual(document.body);
        directive.ngOnChanges();
        tick();
        expect(document.activeElement).toEqual(document.body);
    }));
});
Example #11
Source File: angular-context.ts    From s-libs with MIT License 6 votes vote down vote up
#runWithMockedTime(test: VoidFunction): void {
    // https://github.com/angular/angular/issues/31677#issuecomment-573139551
    const { now } = performance;
    spyOn(performance, 'now').and.callFake(() => Date.now());

    jasmine.clock().install();
    fakeAsync(() => {
      jasmine.clock().mockDate(this.startTime);
      test();
    })();
    jasmine.clock().uninstall();

    performance.now = now;
  }
Example #12
Source File: leaderboard.service.spec.ts    From one-platform with MIT License 6 votes vote down vote up
describe('LeaderboardService', () => {
  let service: LeaderboardService;
  let controller: ApolloTestingController;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [ApolloTestingModule],
    });
    service = TestBed.inject(LeaderboardService);
    controller = TestBed.inject(ApolloTestingController);
  });

  afterEach(() => {
    controller.verify();
  });

  it('should be created', () => {
    expect(service).toBeTruthy();
  });

  it('expect and answer', fakeAsync(() => {
    service
      .listLHLeaderboard(LeaderboardCategory.ACCESSIBILITY)
      .subscribe((leaderboard) => {
        const data = leaderboard.data.listLHLeaderboard;
        expect(data.count).toEqual(1);
      });
    flushMicrotasks();
    const op = controller.expectOne(ListLHLeaderboard);
    expect(op.operation.variables.type).toEqual(
      LeaderboardCategory.ACCESSIBILITY
    );

    op.flush({ data: { listLHLeaderboard: mockLeaderboardData } });

    controller.verify();
  }));
});
Example #13
Source File: user-page.component.spec.ts    From nestjs-angular-starter with MIT License 6 votes vote down vote up
describe('UserPageComponent', () => {
  let component: UserPageComponent;
  let appService: AppService;
  let fixture: ComponentFixture<UserPageComponent>;
  let htmlElement: HTMLElement;

  let heading: HTMLElement;

  beforeEach(async(() => {
    getCommonTestBed([UserPageComponent], []).compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(UserPageComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();

    appService = TestBed.inject(AppService);
    htmlElement = fixture.debugElement.nativeElement;
    heading = htmlElement.querySelector('.jumbotron-heading');
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });

  it('should render the correct user email', fakeAsync(() => {
    // Create a mock user with the email we expect to receive when the user is connected
    spyOnProperty(appService, 'user').and.returnValue({
      email: '[email protected]',
    });

    fixture.detectChanges();
    expect(heading.textContent).toEqual('Hello there [email protected]');
  }));
});
Example #14
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 #15
Source File: user.effects.spec.ts    From router with MIT License 5 votes vote down vote up
describe('UserEffects', () => {
  let effects: UserEffects;
  const eventsMap: { [key: string]: any } = {};

  beforeAll(() => {
    document.addEventListener = jest.fn((event, cb) => {
      eventsMap[event] = cb;
    });
  });

  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [UserEffects],
    });

    effects = TestBed.inject(UserEffects);
  });

  describe('idle$', () => {
    it('should trigger idleTimeout action after 5 minutes', fakeAsync(() => {
      let action: Action | undefined;
      effects.idle$.subscribe((res) => (action = res));

      // Initial action to trigger the effect
      eventsMap['click']();

      tick(2 * 60 * 1000);
      expect(action).toBeUndefined();

      tick(3 * 60 * 1000);
      expect(action).toBeDefined();
      expect(action!.type).toBe(UserActions.idleTimeout.type);
    }));

    it('should reset timeout on user activity', fakeAsync(() => {
      let action: Action | undefined;
      effects.idle$.subscribe((res) => (action = res));

      // Initial action to trigger the effect
      eventsMap['keydown']();

      tick(4 * 60 * 1000);
      eventsMap['mousemove']();

      tick(4 * 60 * 1000);
      expect(action).toBeUndefined();

      tick(1 * 60 * 1000);
      expect(action).toBeDefined();
      expect(action!.type).toBe(UserActions.idleTimeout.type);
    }));
  });
});
Example #16
Source File: container.spec.ts    From slate-angular with MIT License 5 votes vote down vote up
describe('ViewContainer Class', () => {
    let component: AdvancedEditableComponent;
    let fixture: ComponentFixture<AdvancedEditableComponent>;
    let editor: Editor;

    beforeEach(fakeAsync(() => {
        configureBasicEditableTestingModule([AdvancedEditableComponent, TestingLeafComponent], [TestingLeafComponent]);
        fixture = TestBed.createComponent(AdvancedEditableComponent);
        component = fixture.componentInstance;
        component.value = createMutipleParagraph();
        editor = component.editor;
    }));
    
    describe('move nodes', () => {
        it('move node from [0] to [1]', fakeAsync(() => {
            fixture.detectChanges();
            flush();
            fixture.detectChanges();
            const parent = AngularEditor.toDOMNode(editor, editor);
            Transforms.moveNodes(editor, { at: [0], to: [1] });
            fixture.detectChanges();
            flush();
            fixture.detectChanges();
            expect(Node.string(editor.children[0])).toEqual('1');
            const newP0 = parent.children.item(0) as HTMLElement;
            const newP1 = parent.children.item(1) as HTMLElement;
            expect(newP0.textContent).toEqual('1');
            expect(newP1.textContent).toEqual('0');
        }));
        it('move node from [2] to [5]', fakeAsync(() => {
            fixture.detectChanges();
            flush();
            fixture.detectChanges();
            const parent = AngularEditor.toDOMNode(editor, editor);
            Transforms.moveNodes(editor, { at: [2], to: [5] });
            fixture.detectChanges();
            flush();
            fixture.detectChanges();
            const newP5 = parent.children.item(5) as HTMLElement;
            const newP3 = parent.children.item(3) as HTMLElement;
            expect(newP5.textContent).toEqual('2');
            expect(newP3.textContent).toEqual('4');
        }));
        it('move node from [5] to [2]', fakeAsync(() => {
            fixture.detectChanges();
            flush();
            fixture.detectChanges();
            const parent = AngularEditor.toDOMNode(editor, editor);
            Transforms.moveNodes(editor, { at: [5], to: [2] });
            fixture.detectChanges();
            flush();
            fixture.detectChanges();
            const newP2 = parent.children.item(2) as HTMLElement;
            const newP5 = parent.children.item(5) as HTMLElement;
            expect(newP2.textContent).toEqual('5');
            expect(newP5.textContent).toEqual('4');
        }));
    });
});
Example #17
Source File: abstract-navigator.spec.ts    From auth0-angular with MIT License 5 votes vote down vote up
describe('RouteNavigator', () => {
  let navigator: AbstractNavigator;
  let replaceStateSpy: any;

  // Stub component for the sake of getting the router to accept routes
  @Component({})
  class StubComponent {}

  describe('with no router', () => {
    beforeEach(() => {
      TestBed.configureTestingModule({});

      navigator = TestBed.inject(AbstractNavigator);

      const location = TestBed.inject(Location);
      replaceStateSpy = spyOn(location, 'replaceState');
    });

    it('should be created', () => {
      expect(navigator).toBeTruthy();
    });

    it('should use the window object when navigating', async () => {
      await navigator.navigateByUrl('/test-url');

      expect(replaceStateSpy).toHaveBeenCalledWith('/test-url');
    });
  });

  describe('with a router', () => {
    beforeEach(() => {
      TestBed.configureTestingModule({
        imports: [
          RouterTestingModule.withRoutes([
            {
              path: 'test-route',
              component: StubComponent,
            },
          ]),
        ],
      });

      navigator = TestBed.inject(AbstractNavigator);

      const location = TestBed.inject(Location);
      replaceStateSpy = spyOn(location, 'replaceState');
    });

    it('should use the router if available', fakeAsync(() => {
      const location = TestBed.inject(Location);
      navigator.navigateByUrl('/test-route');
      tick();
      expect(location.path()).toBe('/test-route');
    }));

    it('should not use the window object to navigate', async () => {
      expect(replaceStateSpy).not.toHaveBeenCalled();
    });
  });
});
Example #18
Source File: radio.component.spec.ts    From alauda-ui with MIT License 5 votes vote down vote up
describe('RadioComponent', () => {
  let fixture: ComponentFixture<TestComponent>;
  let ins: TestComponent;
  let buttonDebug: DebugElement;
  let buttonEl: HTMLButtonElement;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [RadioModule, FormsModule],
      declarations: [TestComponent],
    });
    fixture = TestBed.createComponent(TestComponent);
    fixture.detectChanges();
    ins = fixture.componentInstance;
    buttonDebug = fixture.debugElement.query(By.css('.aui-radio-button'));
    buttonEl = buttonDebug.nativeElement;
  });

  it('should render correct size class in aui-radio-button', () => {
    const sizeList = [RadioSize.Medium, RadioSize.Small];
    for (const size of sizeList) {
      ins.size = size;
      fixture.detectChanges();
      expect(buttonEl.classList).toContain(`aui-radio-button--${size}`);
    }
  });

  it('should render correct disabled class in aui-radio', fakeAsync(() => {
    const disabledRadioBtn = fixture.debugElement.query(
      By.css('.aui-radio-button.isDisabled'),
    );
    expect(disabledRadioBtn).toBeNull();
    ins.disabled = true;
    fixture.detectChanges();
    tick();
    expect(disabledRadioBtn).toBeDefined();
  }));

  it('should ngModel work', fakeAsync(() => {
    (
      fixture.debugElement.query(By.css('#btn2 input'))
        .nativeElement as HTMLElement
    ).dispatchEvent(new Event('click'));
    fixture.detectChanges();
    expect(
      (
        fixture.debugElement.query(By.css('#btn2 .aui-radio-button'))
          .nativeElement as HTMLElement
      ).classList,
    ).toContain('isChecked');
    expect(ins.food).toEqual('8');

    ins.food = '7';
    fixture.detectChanges();
    tick();
    fixture.detectChanges();
    expect(
      (
        fixture.debugElement.query(By.css('#btn1 .aui-radio-button'))
          .nativeElement as HTMLElement
      ).classList,
    ).toContain('isChecked');

    (
      fixture.debugElement.query(By.css('#btn3 input'))
        .nativeElement as HTMLElement
    ).dispatchEvent(new Event('click'));
    fixture.detectChanges();
    expect(
      (
        fixture.debugElement.query(By.css('#btn3 .aui-radio-button'))
          .nativeElement as HTMLElement
      ).classList,
    ).toContain('isChecked');
  }));
});
Example #19
Source File: accessibility.spec.ts    From frontend-frameworks with MIT License 5 votes vote down vote up
describe('accessibility', () => {
  let component: CloudinaryImageComponent;
  let fixture: ComponentFixture<CloudinaryImageComponent>;

  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [ CloudinaryImageComponent ],
    });
    fixture = TestBed.createComponent(CloudinaryImageComponent);
    component = fixture.componentInstance;
  });

  it('should apply default', fakeAsync(() => {
    component.cldImg = cloudinaryImage;
    component.plugins = [accessibility()];
    fixture.detectChanges();
    tick(0);
    const imgElement: HTMLImageElement = fixture.nativeElement;
    const img = imgElement.querySelector('img');
    expect(img.src).toBe('https://res.cloudinary.com/demo/image/upload/co_black,e_colorize:70/sample');
  }));

  it('should apply darkmode', fakeAsync(() => {
    component.cldImg = cloudinaryImage;
    component.plugins = [accessibility({mode: 'darkmode'})];
    fixture.detectChanges();
    tick(0);
    const imgElement: HTMLImageElement = fixture.nativeElement;
    const img = imgElement.querySelector('img');
    expect(img.src).toBe('https://res.cloudinary.com/demo/image/upload/co_black,e_colorize:70/sample');
  }));

  it('should apply brightmode', fakeAsync(() => {
    component.cldImg = cloudinaryImage;
    component.plugins = [accessibility({mode: 'brightmode'})];
    fixture.detectChanges();
    tick(0);
    const imgElement: HTMLImageElement = fixture.nativeElement;
    const img = imgElement.querySelector('img');
    expect(img.src).toBe('https://res.cloudinary.com/demo/image/upload/co_white,e_colorize:40/sample');
  }));

  it('should apply monochrome', fakeAsync(() => {
    component.cldImg = cloudinaryImage;
    component.plugins = [accessibility({mode: 'monochrome'})];
    fixture.detectChanges();
    tick(0);
    const imgElement: HTMLImageElement = fixture.nativeElement;
    const img = imgElement.querySelector('img');
    expect(img.src).toBe('https://res.cloudinary.com/demo/image/upload/e_grayscale/sample');
  }));

  it('should apply colorblind', fakeAsync(() => {
    component.cldImg = cloudinaryImage;
    component.plugins = [accessibility({mode: 'colorblind'})];
    fixture.detectChanges();
    tick(0);
    const imgElement: HTMLImageElement = fixture.nativeElement;
    const img = imgElement.querySelector('img');
    expect(img.src).toBe('https://res.cloudinary.com/demo/image/upload/e_assist_colorblind/sample');
  }));

  it('should default if supplied with incorrect mode', fakeAsync(() => {
    component.cldImg = cloudinaryImage;
    component.plugins = [accessibility({mode: 'ddd'})];
    fixture.detectChanges();
    tick(0);
    const imgElement: HTMLImageElement = fixture.nativeElement;
    const img = imgElement.querySelector('img');
    expect(img.src).toBe('https://res.cloudinary.com/demo/image/upload/co_black,e_colorize:70/sample');
  }));
});
Example #20
Source File: ngx-tippy-singleton.spec.ts    From ngx-tippy-wrapper with MIT License 5 votes vote down vote up
describe('Component: NgxTippySingletonComponent (wrapped)', () => {
  let injector: TestBed;
  let fixture: ComponentFixture<TestWrapperComponent>;
  let component: TestWrapperComponent;
  let debugEl: DebugElement;

  beforeEach(async () => {
    TestBed.configureTestingModule({
      declarations: [NgxTippyDirective, NgxTippySingletonComponent, TestWrapperComponent],
      providers: [
        NgxTippyService,
        {
          provide: NGX_TIPPY_MESSAGES,
          useValue: messagesDict,
        },
      ],
    })
      .compileComponents()
      .then(() => {
        injector = getTestBed();
        fixture = injector.createComponent(TestWrapperComponent);
        component = fixture.componentInstance;
        debugEl = fixture.debugElement;
        fixture.detectChanges();
      });
  });

  it('should create wrapper test component', () => {
    expect(component).toBeTruthy();
  });

  it('should render all grouped elements', () => {
    const singletonItems = debugEl.queryAll(By.css('button[data-tippy-singleton]'));

    expect(singletonItems).toBeTruthy();
    expect(singletonItems.length).toBe(3);
  });

  it('should show tooltips on hover', () => {
    const singletonItems = debugEl.queryAll(By.css('button[data-tippy-singleton]'));
    singletonItems.forEach(el => {
      el.nativeElement.dispatchEvent(new MouseEvent('mouseenter'));
    });
    fixture.detectChanges();
    const tooltips = fixture.debugElement.queryAll(By.css('div[data-tippy-root]'));

    expect(tooltips).toBeTruthy();
    expect(tooltips.length).toBe(1);
  });

  it('should apply properties', fakeAsync(() => {
    const singletonItems = debugEl.queryAll(By.css('button[data-tippy-singleton]'));
    singletonItems.forEach(el => {
      el.nativeElement.dispatchEvent(new MouseEvent('mouseenter'));
    });
    fixture.detectChanges();

    const tooltipArrow = fixture.debugElement.query(By.css('.tippy-arrow'));
    const tippyBox = fixture.debugElement.query(By.css('.tippy-box'));
    const tooltipBgColor = getComputedStyle(tippyBox.nativeElement).backgroundColor;

    expect(tooltipArrow).toBeNull();
    expect(tooltipBgColor).toBe('rgb(255, 255, 255)');

    let dataPlacement!: string;

    setTimeout(() => {
      dataPlacement = tippyBox.nativeElement.dataset.placement;
    }, 0);
    tick(0);

    expect(dataPlacement).toBe('top');
  }));
});
Example #21
Source File: log-timers.spec.ts    From s-libs with MIT License 5 votes vote down vote up
describe('logTimers()', () => {
  it('prints each timeout call to `console.log`', fakeAsync(() => {
    const logSpy = spyOn(console, 'log');
    const stopLogging = logTimers();

    setTimeout(myFunction);
    expectSingleCallAndReset(logSpy, 'setTimeout(', myFunction, ')');

    setTimeout(myDelayedFunction, 1000);
    expectSingleCallAndReset(
      logSpy,
      'setTimeout(',
      myDelayedFunction,
      1000,
      ')',
    );

    tick(1000);
    stopLogging();

    // eslint-disable-next-line @typescript-eslint/no-empty-function
    function myFunction(): void {}

    // eslint-disable-next-line @typescript-eslint/no-empty-function
    function myDelayedFunction(): void {}
  }));

  it('prints each interval call to `console.log`', fakeAsync(() => {
    const logSpy = spyOn(console, 'log');
    const stopLogging = logTimers();

    setInterval(myFunction);
    expectSingleCallAndReset(logSpy, 'setInterval(', myFunction, ')');

    setInterval(myDelayedFunction, 1000);
    expectSingleCallAndReset(
      logSpy,
      'setInterval(',
      myDelayedFunction,
      1000,
      ')',
    );

    discardPeriodicTasks();
    stopLogging();

    // eslint-disable-next-line @typescript-eslint/no-empty-function
    function myFunction(): void {}

    // eslint-disable-next-line @typescript-eslint/no-empty-function
    function myDelayedFunction(): void {}
  }));

  it('returns a function to stop the logging', () => {
    const logSpy = spyOn(console, 'log');

    const stopLogging = logTimers();
    stopLogging();

    setTimeout(noop);
    setInterval(noop);
    expect(logSpy).not.toHaveBeenCalled();
  });
});
Example #22
Source File: sticky-header.component.spec.ts    From geonetwork-ui with GNU General Public License v2.0 5 votes vote down vote up
describe('StickyHeaderComponent', () => {
  let component: StickyHeaderComponent
  let componentDebugEl: DebugElement
  let fixture: ComponentFixture<ContainerComponent>

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [ContainerComponent, StickyHeaderComponent],
    }).compileComponents()
  })

  beforeEach(() => {
    fixture = TestBed.createComponent(ContainerComponent)
    componentDebugEl = fixture.debugElement.query(
      By.directive(StickyHeaderComponent)
    )
    component = componentDebugEl.componentInstance
    fixture.detectChanges()
  })

  it('should create', () => {
    expect(component).toBeTruthy()
  })

  it('contains the header text in the template', () => {
    const content = componentDebugEl.nativeElement.textContent
    expect(content.trim()).toBe('This is the header text.')
  })

  describe('size update', () => {
    let headerEl: HTMLElement
    let containerEl: HTMLElement
    let contentEl: HTMLElement
    beforeEach(() => {
      headerEl = component.innerContainer.nativeElement
      containerEl = fixture.nativeElement.children[0]
      contentEl = fixture.debugElement.query(By.css('.content')).nativeElement
    })
    describe('at initialization', () => {
      it('sets height at full height', () => {
        expect(headerEl.style.height).toBe('300px')
      })
      it('sets opacity using expandRatio', () => {
        expect(contentEl.style.opacity).toBe('1')
      })
    })
    describe('after partial scroll', () => {
      beforeEach(fakeAsync(() => {
        containerEl.scrollTop = 50
        containerEl.dispatchEvent(new Event('scroll'))
        tick(20)
      }))
      it('sets height between full and min height', () => {
        expect(headerEl.style.transform).toBe('translate(0, -50px)')
      })
      it('sets opacity using expandRatio', () => {
        expect(contentEl.style.opacity).toBe('0.75')
      })
    })
    describe('after complete scroll', () => {
      beforeEach(fakeAsync(() => {
        containerEl.scrollTop = 250
        containerEl.dispatchEvent(new Event('scroll'))
        tick(20)
      }))
      it('sets height at min height', () => {
        expect(headerEl.style.transform).toBe('translate(0, -200px)')
      })
      it('sets opacity using expandRatio', () => {
        expect(contentEl.style.opacity).toBe('0')
      })
    })
  })
})
Example #23
Source File: context-selector.component.spec.ts    From one-platform with MIT License 5 votes vote down vote up
describe('ContextSelectorComponent', () => {
  let component: ContextSelectorComponent;
  let fixture: ComponentFixture<ContextSelectorComponent>;

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [ContextSelectorComponent],
    }).compileComponents();
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(ContextSelectorComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });

  it('default values for context select', () => {
    expect(component.isOpen).toBeFalsy();
    expect(component.searchInputValue).toBe('');
    expect(component.toggleText).toBe('');
  });

  it('should be hidden', () => {
    fixture.detectChanges();
    fixture.whenStable().then(() => {
      const el = fixture.debugElement.query(
        By.css('.pf-c-context-selector__menu')
      );
      expect(el).toBeNull();
    });
  });

  it('should reveal options', fakeAsync(() => {
    component.isOpen = true;
    tick();
    fixture.detectChanges();
    expect(component.isOpen).toBeTruthy();
    const el = fixture.debugElement.query(
      By.css('.pf-c-context-selector__menu')
    );
    expect(el).toBeTruthy();
  }));
});
Example #24
Source File: auth.service.spec.ts    From jira-clone-angular with MIT License 5 votes vote down vote up
describe('AuthService', () => {
  let service: AuthService;

  const httpClient: any = {
    get: jasmine.createSpy('get')
  };
  const authStore: any = {
    setLoading: jasmine.createSpy('setLoading').and.callThrough(),
    update: jasmine.createSpy('update').and.callThrough(),
    setError: jasmine.createSpy('setError').and.callThrough()
  };

  beforeEach(() => {
    service = new AuthService(
      httpClient,
      authStore
    );
  });

  it('should be able to login', () => {
    const data = new Subject();
    httpClient.get.and.returnValue(data);
    service.login({
      email: '',
      password: '',
    });
    expect(authStore.setLoading).toHaveBeenCalledWith(true);
    data.next({
      id: '',
      name: '',
      email: '',
      avatarUrl: '',
      createdAt: '',
      updatedAt: '',
      issueIds: []
    });
    expect(httpClient.get).toHaveBeenCalledWith('/assets/data/auth.json');
    expect(authStore.update).toHaveBeenCalled();
  });
  it('should not be able to login', fakeAsync(() => {
    const data = new Subject();
    httpClient.get.and.returnValue(data);
    service.login({
      email: '',
      password: '',
    });
    authStore.update.and.callFake(() => {
      throw new Error('Something bad happened');
    });
    expect(authStore.setLoading).toHaveBeenCalledWith(true);
    authStore.setLoading.calls.reset();
    data.next({
      id: '',
      name: '',
      email: '',
      avatarUrl: '',
      createdAt: '',
      updatedAt: '',
      issueIds: []
    });

    expect(authStore.setLoading).toHaveBeenCalledWith(false);
    expect(authStore.setError).toHaveBeenCalled();
  }));
});
Example #25
Source File: outlined-pie-graph.component.spec.ts    From one-platform with MIT License 5 votes vote down vote up
describe('OutlinedPieGraphComponent', () => {
  let component: OutlinedPieGraphComponent;
  let fixture: ComponentFixture<OutlinedPieGraphComponent>;
  const mockName = 'pwa';

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [OutlinedPieGraphComponent],
    }).compileComponents();
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(OutlinedPieGraphComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });

  it('should have default score', () => {
    expect(component.score).toBe(0);
  });

  it('should have name', fakeAsync(() => {
    component.name = mockName;
    tick();
    fixture.detectChanges();
    const el: HTMLElement = fixture.nativeElement;
    expect(el.textContent).toContain(mockName);
  }));

  it('should show red on score below 49', fakeAsync(() => {
    component.score = 40;
    tick();
    fixture.detectChanges();
    const el: HTMLElement = fixture.nativeElement;
    const graph = el.querySelector('.gauge-circle-chart.low .gauge-circle');
    expect(graph).toBeTruthy();
  }));

  it('should show red on score below 90', fakeAsync(() => {
    component.score = 60;
    tick();
    fixture.detectChanges();
    const el: HTMLElement = fixture.nativeElement;
    const graph = el.querySelector('.gauge-circle-chart.average .gauge-circle');
    expect(graph).toBeTruthy();
  }));

  it('should show red on score above 90', fakeAsync(() => {
    component.score = 92;
    tick();
    fixture.detectChanges();
    const el: HTMLElement = fixture.nativeElement;
    const graph = el.querySelector('.gauge-circle-chart.best .gauge-circle');
    expect(graph).toBeTruthy();
  }));
});
Example #26
Source File: angular-editor.spec.ts    From slate-angular with MIT License 5 votes vote down vote up
describe('AngularEditor', () => {
    let component: BasicEditableComponent;
    let fixture: ComponentFixture<BasicEditableComponent>;

    beforeEach(fakeAsync(() => {
        configureBasicEditableTestingModule([BasicEditableComponent]);
        fixture = TestBed.createComponent(BasicEditableComponent);
        component = fixture.componentInstance;
        component.value = createEmptyDocument() as Element[];
        fixture.detectChanges();
        flush();
        fixture.detectChanges();
    }));

    afterEach(() => {
        fixture.destroy();
    });

    it('should fixed cursor after zero width char when text node is empty', () => {
        Transforms.select(component.editor, {
            anchor: {
                path: [0, 0],
                offset: 0
            },
            focus: {
                path: [0, 0],
                offset: 0
            }
        });
        const nativeRange = AngularEditor.toDOMRange(component.editor, component.editor.selection);
        expect(nativeRange.startOffset).toEqual(1);
        expect(nativeRange.endOffset).toEqual(1);
    });

    it('should fixed cursor to location after inserted text when insertText', fakeAsync(() => {
        const insertText = 'test';
        Transforms.select(component.editor, {
            anchor: {
                path: [0, 0],
                offset: 0
            },
            focus: {
                path: [0, 0],
                offset: 0
            }
        });
        tick(100);
        Transforms.insertText(component.editor, insertText);
        tick(100);
        const nativeRange = AngularEditor.toDOMRange(component.editor, component.editor.selection);
        expect(nativeRange.startOffset).toEqual(insertText.length);
        expect(nativeRange.endOffset).toEqual(insertText.length);
    }));
});
Example #27
Source File: checkbox-group.component.spec.ts    From alauda-ui with MIT License 5 votes vote down vote up
describe('CheckboxGroupComponent', () => {
  let fixture: ComponentFixture<TestComponent>;
  let ins: TestComponent;
  let el1: HTMLElement;
  let el2: HTMLElement;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [FormsModule, CheckboxModule],
      declarations: [TestComponent],
    });
    fixture = TestBed.createComponent(TestComponent);
    fixture.detectChanges();
    ins = fixture.componentInstance;
    el1 = fixture.debugElement.query(
      By.css('.group1 aui-checkbox-group'),
    ).nativeElement;
    el2 = fixture.debugElement.query(
      By.css('.group2 aui-checkbox-group'),
    ).nativeElement;
  });

  it('should checkbox init checked state by value array', fakeAsync(() => {
    ins.value = ['box1', 'box2', 'box3'];
    fixture.detectChanges();
    tick();
    fixture.detectChanges();

    const boxes = el1.querySelectorAll('.aui-checkbox');
    expect(boxes.item(0).className).not.toContain('isChecked');
    expect(boxes.item(1).className).toContain('isChecked');
    expect(boxes.item(2).className).toContain('isChecked');
    expect(boxes.item(3).className).toContain('isChecked');
  }));

  it('should value change when checkbox clicked', () => {
    const boxes = el1.querySelectorAll('.aui-checkbox input');
    boxes.item(0).dispatchEvent(new Event('click'));
    boxes.item(1).dispatchEvent(new Event('click'));
    boxes.item(2).dispatchEvent(new Event('click'));
    boxes.item(3).dispatchEvent(new Event('click'));
    fixture.detectChanges();

    expect(ins.value).toEqual(['box0', 'box1', 'box2']);
  });

  it('should checkbox init checked state by collection', fakeAsync(() => {
    ins.value2 = [{ name: 'box2' }];
    fixture.detectChanges();
    tick();
    fixture.detectChanges();

    const boxes = el2.querySelectorAll('.aui-checkbox');
    expect(boxes.item(0).className).not.toContain('isChecked');
    expect(boxes.item(1).className).toContain('isChecked');
    expect(boxes.item(2).className).not.toContain('isChecked');
  }));
});
Example #28
Source File: options-debug-section.component.spec.ts    From WowUp with GNU General Public License v3.0 5 votes vote down vote up
describe("OptionsDebugSectionComponent", () => {
  let component: OptionsDebugSectionComponent;
  let fixture: ComponentFixture<OptionsDebugSectionComponent>;
  let addonServiceSpy: any;
  let wowUpServiceSpy: any;
  let sessionService: any;

  beforeEach(async () => {
    addonServiceSpy = jasmine.createSpyObj(AddonService, ["logDebugData"]);
    wowUpServiceSpy = jasmine.createSpyObj(WowUpService, ["showLogsFolder"]);
    sessionService = jasmine.createSpyObj("SessionService", [""], {});

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

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

    fixture.detectChanges();
  });

  it("should create", () => {
    expect(component).toBeTruthy();
  });

  it("Should call logDebugData", fakeAsync(() => {
    const button = fixture.debugElement.nativeElement.querySelector("#dump-debug-btn");
    button.click();
    tick();
    expect(addonServiceSpy.logDebugData).toHaveBeenCalled();
  }));

  it("Should call showLogFiles", fakeAsync(() => {
    const button = fixture.debugElement.nativeElement.querySelector("#show-log-btn");
    button.click();
    tick();
    expect(wowUpServiceSpy.showLogsFolder).toHaveBeenCalled();
  }));
});
Example #29
Source File: playground.service.spec.ts    From one-platform with MIT License 5 votes vote down vote up
describe('PlaygroundService', () => {
  let service: PlaygroundService;
  let controller: ApolloTestingController;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [ApolloTestingModule],
    });
    service = TestBed.inject(PlaygroundService);
    controller = TestBed.inject(ApolloTestingController);
  });

  it('should be created', () => {
    expect(service).toBeTruthy();
  });

  it('AuditWebsite mutation', fakeAsync(() => {
    service
      .auditWebsite(mockAuditWebsiteInput.property)
      .subscribe((auditId) => {
        expect(auditId).toEqual(mockAuditWebsite.data);
      });
    flushMicrotasks();
    const op = controller.expectOne((operation) => {
      expect(operation.query.definitions).toEqual(AuditWebsite.definitions);
      return true;
    });
    expect(op.operation.variables.property).toEqual(
      mockAuditWebsiteInput.property
    );

    op.flush({ data: mockAuditWebsite.data });

    controller.verify();
  } ) );

  it('Autorun subscription', fakeAsync(() => {
    service
      .autorun()
      .subscribe((doc) => {
        expect(doc).toEqual(mockAutorun.data.autorun);
      });
    flushMicrotasks();
    const op = controller.expectOne((operation) => {
      expect(operation.query.definitions).toEqual(Autorun.definitions);
      return true;
    });

    op.flush({ data: mockAutorun.data });

    controller.verify();
  }));
});