@angular/core/testing#tick TypeScript Examples

The following examples show how to use @angular/core/testing#tick. 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: dispatchResize.ts    From frontend-frameworks with MIT License 6 votes vote down vote up
/**
 * Dispatches resize event
 * @param width {string}  width to resize to
 * @param fixture {any} The current fixture
 * @param time {number} The timout
 */
export function dispatchResize(width: string, fixture: any, time: number){
  document.body.style.width = width;
  window.dispatchEvent(new Event('resize'));
  fixture.detectChanges();
  tick(time);
}
Example #3
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 #4
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 #5
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 #6
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 #7
Source File: angular-context.ts    From s-libs with MIT License 6 votes vote down vote up
/**
   * Advance time and trigger change detection. It is common to call this with no arguments to trigger change detection without advancing time.
   *
   * @param unit The unit of time `amount` represents. Accepts anything described in `@s-libs/s-core`'s [TimeUnit]{@linkcode https://simontonsoftware.github.io/s-js-utils/typedoc/enums/timeunit.html} enum.
   */
  tick(amount = 0, unit = 'ms'): void {
    if (
      isUndefined((window as any).Zone.current.get('FakeAsyncTestZoneSpec'))
    ) {
      throw new Error(
        '.tick() only works inside the .run() callback (because it needs to be in a fakeAsync zone)',
      );
    }

    // To simulate real life, trigger change detection before processing macro tasks. To further simulate real life, wait until the micro task queue is empty.
    flushMicrotasks();
    this.runChangeDetection();

    tick(convertTime(amount, unit, 'ms'));
    this.runChangeDetection();
  }
Example #8
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 #9
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 #10
Source File: angular-context.ts    From s-libs with MIT License 6 votes vote down vote up
/**
   * Runs `test` in a `fakeAsync` zone. It can use async/await, but be sure anything you `await` is already due to execute (e.g. if a timeout is due in 3 seconds, call `.tick(3000)` before `await`ing its result).
   *
   * Also runs the following in this order, all within the same zone:
   *
   * 1. `this.init()`
   * 2. `test()`
   * 3. `this.verifyPostTestConditions()`
   * 4. `this.cleanUp()`
   */
  run(test: () => Promise<void> | void): void {
    this.#runWithMockedTime(() => {
      this.init();
      try {
        test();
        this.tick();
        this.verifyPostTestConditions();
      } finally {
        this.cleanUp();
      }
    });
  }
Example #11
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 #12
Source File: test_utils.ts    From nestjs-angular-starter with MIT License 6 votes vote down vote up
export function tickAndDetectChanges(fixture: ComponentFixture<unknown>): void {
  tick();
  fixture.detectChanges();
}
Example #13
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 #14
Source File: angular-context.ts    From s-libs with MIT License 5 votes vote down vote up
protected runChangeDetection(): void {
    this.inject(ApplicationRef).tick();
  }
Example #15
Source File: cloudinary-image.component.spec.ts    From frontend-frameworks with MIT License 5 votes vote down vote up
describe('CloudinaryImageComponent render', () => {
  let component: CloudinaryImageComponent;
  let fixture: ComponentFixture<CloudinaryImageComponent>;

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

  it('should render image', 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')
  }));

  it('ngOnChanges should trigger plugin rerun', fakeAsync(() => {
    component.cldImg = cloudinaryImage;
    const mockPlugin = jasmine.createSpy('spy');
    component.plugins = [mockPlugin];
    fixture.detectChanges();
    tick(0);

    // plugins called once
    expect(mockPlugin).toHaveBeenCalledTimes(1);

    // trigger ngOnChanges
    component.ngOnChanges();

    // plugins should be called twice after onChange
    expect(mockPlugin).toHaveBeenCalledTimes(2);
  }));

  it('should add attributes to image', fakeAsync(() => {
    component.cldImg = cloudinaryImage;
    component.width = '400px';
    component.alt = 'text text text';
    component.height = '500px';
    component.loading = 'eager';
    fixture.detectChanges();
    tick(0);
    const imgElement: HTMLImageElement = fixture.nativeElement;
    const img = imgElement.querySelector('img');
    expect(img.outerHTML).toBe('<img _ngcontent-a-c11="" alt="text text text" width="400px" height="500px"' +
      ' loading="eager" src="https://res.cloudinary.com/demo/image/upload/sample">');
  }));
});
Example #16
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 #17
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 #18
Source File: switch.component.spec.ts    From alauda-ui with MIT License 5 votes vote down vote up
describe('SwitchComponent', () => {
  let fixture: ComponentFixture<TestComponent>;
  let ins: TestComponent;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [SwitchModule, FormsModule],
      declarations: [TestComponent],
    });
    fixture = TestBed.createComponent(TestComponent);
    fixture.detectChanges();
    ins = fixture.componentInstance;
  });

  it('should render correct with click event', () => {
    // not-switched => switched
    (
      fixture.debugElement.query(By.css('#switch2 .aui-switch'))
        .nativeElement as HTMLElement
    ).dispatchEvent(new Event('click'));
    fixture.detectChanges();
    expect(
      (
        fixture.debugElement.query(By.css('#switch2 .aui-switch'))
          .nativeElement as HTMLElement
      ).className,
    ).toContain('isChecked');

    // switched => not-switched
    (
      fixture.debugElement.query(By.css('#switch1 .aui-switch'))
        .nativeElement as HTMLElement
    ).dispatchEvent(new Event('click'));
    fixture.detectChanges();
    expect(
      (
        fixture.debugElement.query(By.css('#switch1 .aui-switch'))
          .nativeElement as HTMLElement
      ).className,
    ).not.toContain('isChecked');

    // disabled: switched => switched
    (
      fixture.debugElement.query(By.css('#switch3 .aui-switch'))
        .nativeElement as HTMLElement
    ).dispatchEvent(new Event('click'));
    fixture.detectChanges();
    expect(
      (
        fixture.debugElement.query(By.css('#switch3 .aui-switch'))
          .nativeElement as HTMLElement
      ).className,
    ).toContain('isChecked');
  });

  it('should render correct with ngModel', fakeAsync(() => {
    (
      fixture.debugElement.query(By.css('#switch4 .aui-switch'))
        .nativeElement as HTMLElement
    ).dispatchEvent(new Event('click'));
    fixture.detectChanges();
    expect(ins.switchMap.d).toBe(false);
    ins.switchMap.d = true;
    fixture.detectChanges();
    tick();
    fixture.detectChanges();
    expect(
      (
        fixture.debugElement.query(By.css('#switch4 .aui-switch'))
          .nativeElement as HTMLElement
      ).className,
    ).toContain('isChecked');
  }));
});
Example #19
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 #20
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 #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: 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 #23
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 #24
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 #25
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 #26
Source File: user-detail.component.spec.ts    From Angular-Cookbook with MIT License 5 votes vote down vote up
describe('UserDetailComponent', () => {
  let component: UserDetailComponent;
  let fixture: ComponentFixture<UserDetailComponent>;
  let activatedRoute;
  beforeEach(
    waitForAsync(() => {
      TestBed.configureTestingModule({
        declarations: [UserDetailComponent, LoaderComponent, UserCardComponent],
        imports: [HttpClientModule, RouterTestingModule],
        providers: [
          {
            provide: UserService,
            useClass: UserServiceMock,
          },
          {
            provide: ActivatedRoute,
            useValue: new ActivatedRouteMock(),
          },
        ],
      }).compileComponents();
    })
  );

  beforeEach(() => {
    fixture = TestBed.createComponent(UserDetailComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
    activatedRoute = TestBed.inject(ActivatedRoute);
  });

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

  it('should get the user based on routeParams on page load', fakeAsync(() => {
    component.ngOnInit();
    activatedRoute.setParamMap({ uuid: DUMMY_USERS[1].login.uuid });
    tick(500);
    expect(component.user).toEqual(DUMMY_USERS[1]);
  }));

  it('should get similar user based on routeParams uuid on page load', fakeAsync(() => {
    component.ngOnInit();
    activatedRoute.setParamMap({ uuid: DUMMY_USERS[1].login.uuid }); // the second user's uuid
    const expectedSimilarUsers = [DUMMY_USERS[0]]; // the first user
    tick(500);
    expect(component.similarUsers).toEqual(expectedSimilarUsers);
  }));
});
Example #27
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 #28
Source File: tags-input.component.spec.ts    From alauda-ui with MIT License 5 votes vote down vote up
describe('TagsInputComponent', () => {
  let fixture: ComponentFixture<TestComponent>;
  let ins: TestComponent;
  let el: HTMLElement;
  let inputEl: HTMLInputElement;

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

  it('should display input values', fakeAsync(() => {
    ins.value = ['app', 'service'];
    fixture.detectChanges();
    tick();
    fixture.detectChanges();
    const tags = el.querySelectorAll('.aui-tag:not(input)');
    expect(tags.item(0).innerHTML).toContain('app');
    expect(tags.item(1).innerHTML).toContain('service');
  }));

  it('should push new value when press Enter', fakeAsync(() => {
    inputEl.value = 'app';
    inputEl.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter' }));
    fixture.detectChanges();
    tick(20);
    fixture.detectChanges();
    expect(ins.value).toEqual(['app']);
  }));

  it('should last tag could be delete by press Backspace', fakeAsync(() => {
    ins.value = ['app'];
    fixture.detectChanges();
    tick();
    inputEl.dispatchEvent(new KeyboardEvent('keydown', { key: 'Backspace' }));
    fixture.detectChanges();
    expect(ins.value).toEqual([]);
  }));

  it('should tag could be delete by click close', fakeAsync(() => {
    ins.value = ['app', 'service'];
    fixture.detectChanges();
    tick();
    fixture.detectChanges();
    const tags = el.querySelectorAll('.aui-tag:not(input)');
    tags
      .item(0)
      .querySelector('.aui-tag__close')
      .dispatchEvent(new Event('click'));
    fixture.detectChanges();
    expect(ins.value).toEqual(['service']);
  }));

  it('should placeholder show or hidden correctly', fakeAsync(() => {
    ins.placeholder = 'placeholder';
    fixture.detectChanges();
    const placeholderEl = el.querySelector('.aui-tags-input__placeholder');
    expect(placeholderEl.innerHTML).toContain('placeholder');
    expect(placeholderEl.getAttribute('hidden')).toBeNull();
    ins.value = ['app', 'service'];
    fixture.detectChanges();
    tick();
    fixture.detectChanges();
    expect(placeholderEl.getAttribute('hidden')).toBe('');
  }));
});
Example #29
Source File: home.component.spec.ts    From one-platform with MIT License 5 votes vote down vote up
describe('HomeComponent', () => {
  let component: HomeComponent;
  let fixture: ComponentFixture<HomeComponent>;
  let service: DashboardService;

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [HomeComponent, PropertyCardComponent],
      imports: [
        RouterTestingModule,
        FormsModule,
        SharedModule,
        ApolloTestingModule,
      ],
    }).compileComponents();
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(HomeComponent);
    component = fixture.componentInstance;
    service = TestBed.inject(DashboardService);
    fixture.detectChanges();
    spyOn(service, 'listLHProjects').and.returnValue(
      of({ data: mockListProjects, loading: false })
    );
    component.ngOnInit();
  });

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

  it('should show list of projects', () => {
    expect(component.projects).toEqual(
      mockListProjects.listLHProjects as any // graphql type error: using general type of the whole object
    );
    expect(component.isProjectListLoading).toBeFalsy();
  });

  it('should show empty banner', fakeAsync(() => {
    const el: HTMLElement = fixture.nativeElement;
    component.isEmpty = true;
    tick();
    fixture.detectChanges();

    expect(el.textContent).toContain('No data found');
  }));

  it('should should loading state', fakeAsync(() => {
    const el: HTMLElement = fixture.nativeElement;
    component.isProjectListLoading = true;
    component.projects = { count: 0, rows: [] };
    tick();
    fixture.detectChanges();
    expect(el.textContent).not.toContain('No data found');
    expect(el.textContent).toContain('Loading...');
  }));
});