@angular/core#SimpleChange TypeScript Examples

The following examples show how to use @angular/core#SimpleChange. 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: ngx-tippy.directive.ts    From ngx-tippy-wrapper with MIT License 6 votes vote down vote up
private handleContentChanges({ currentValue }: SimpleChange) {
    const tippyInstances = this.cachedTippyInstances();

    if (this.tippyInstance && this.tippyName) {
      this.ngxTippyService.setContent(this.tippyName, currentValue);
    } else {
      this.initTippy();
    }

    if (tippyInstances && this.tippyInstance && currentValue === null) {
      this.clearInstance({ tippyInstance: this.tippyInstance, tippyInstances });
    }
  }
Example #2
Source File: lazy-service.service.ts    From ng-ant-admin with MIT License 6 votes vote down vote up
async lazyLoadCard(selPerson: LazySelPeopleEnum = LazySelPeopleEnum.YiLin) {
    const viewContainerRef = this._adHost.viewContainerRef;
    const {LazyTargCompComponent} = await import('./lazy-targ-comp/lazy-targ-comp.component');
    const {instance} = viewContainerRef.createComponent(LazyTargCompComponent);
    instance.purChoosePeople = selPerson;
    instance.currentPeople.pipe(takeUntil(instance.destroy$)).subscribe(() => {
      this.create(instance.purChoosePeople)
    });
    // 实现OnChange钩子
    (instance as any).ngOnChanges({
      purChoosePeople: new SimpleChange(null, instance.purChoosePeople, true)
    });
  }
Example #3
Source File: dyn-control.class.ts    From open-source with MIT License 6 votes vote down vote up
ngOnInit(): void {
    super.ngOnInit();

    // merge any configured paramFns
    if (this.config.paramFns) {
      this.updateParams(undefined, this.config.paramFns);
    }

    // listen parameters changes after the control is ready
    combineLatest([
      isObservable(this.config.params) ? this.config.params : of(this.config.params || {}),
      this.node.paramsUpdates$.pipe(startWith({})),
    ]).pipe(
      scan<any>((params, [config, updates]) => merge(true, params, config, updates)),
      filter(params => !Array.isArray(params)), // filters the first scan
    ).subscribe((params) => {
      // emulates ngOnChanges
      const change = new SimpleChange(this.params, this.completeParams(params), !this.params);
      this.params$.next(change.currentValue);
      this._logger.nodeParamsUpdated(this.node, this.constructor.name, this.params);

      setTimeout(() => {
        // emulates ngOnChanges and async pipe
        this.ngOnChanges({ params: change });
        this.node.markParamsAsLoaded();
        this._ref.markForCheck();
      }, 1);
    });
  }
Example #4
Source File: app-sidenav.component.ts    From youpez-admin with MIT License 6 votes vote down vote up
ngOnChanges(changes: SimpleChanges): void {
    const opened: SimpleChange = changes.originalOpened

    if (opened !== undefined && opened.previousValue !== undefined) {
      const currentOpened = opened.currentValue
      if (currentOpened) {
        this.onOpen()
      }
      else {
        this.onClose()
      }
    }
  }
Example #5
Source File: vg-scrub-bar-cue-points.component.ts    From ngx-videogular with MIT License 5 votes vote down vote up
ngOnChanges(changes: { [propName: string]: SimpleChange }) {
    if (changes.vgCuePoints.currentValue) {
      this.updateCuePoints();
    }
  }
Example #6
Source File: componentUpdater.ts    From ngx-dynamic-hooks with MIT License 5 votes vote down vote up
/**
   * Processes a hook object and updates the inputs of a dynamic component where required
   *
   * @param hook - The hook in question
   * @param options - The current HookComponentOptions
   */
  updateComponentWithNewInputs(hook: Hook, options: OutletOptions): void {
    // Find out which inputs have changed
    const changedInputs = this.getChangedBindings(hook, 'inputs', options.compareInputsByValue, options.compareByValueDepth);

    // Check if inputs exists on component
    const existingInputs = {};
    if (options.acceptInputsForAnyProperty) {
      for (const [inputName, inputValue] of Object.entries(changedInputs)) {
        // Even this setting has limits. Don't allow setting fundamental JavaScript object properties.
        if (!['__proto__', 'prototype', 'constructor'].includes(inputName)) {
          existingInputs[inputName] = inputValue;
        } else {
          console.error('Tried to overwrite a __proto__, prototype or constructor property with input "' + inputName + '" for hook "' + hook.componentRef.componentType.name + '". This is not allowed.');
          continue;
        }
      }
    } else {
      const compFactory = this.cfr.resolveComponentFactory(hook.componentRef.componentType);
      for (const [inputName, inputValue] of Object.entries(changedInputs)) {
        const inputEntry = compFactory.inputs.filter(inputObject => inputName === (options.ignoreInputAliases ? inputObject.propName : inputObject.templateName));
        if (inputEntry.length > 0) {
          // Save in existingInputs with actual property name, not alias
          existingInputs[inputEntry[0].propName] = inputValue;
        }
      }
    }

    // Pass in Inputs, create SimpleChanges object
    const simpleChanges: {[key: string]: SimpleChange} = {};
    for (const [inputName, inputValue] of Object.entries(existingInputs)) {
      hook.componentRef.instance[inputName] = inputValue;
      const previousValue = hook.previousBindings && hook.previousBindings.inputs.hasOwnProperty(inputName) ? hook.previousBindings.inputs[inputName].reference : undefined;
      simpleChanges[inputName] = new SimpleChange(previousValue, inputValue, !hook.dirtyInputs.has(inputName));
      hook.dirtyInputs.add(inputName);
    }

    // Call ngOnChanges()
    if (Object.keys(simpleChanges).length > 0 && typeof hook.componentRef.instance['ngOnChanges'] === 'function') {
      hook.componentRef.instance.ngOnChanges(simpleChanges);
    }
  }
Example #7
Source File: issue-title.component.spec.ts    From jira-clone-angular with MIT License 5 votes vote down vote up
describe('IssueTitleComponent', () => {
  let component: IssueTitleComponent;

  const projectService: any = {
    updateIssue: jasmine.createSpy('updateIssue').and.callThrough()
  };

  beforeEach(() => {
    component = new IssueTitleComponent(
      projectService
    );
    component.titleControl = new FormControl('test');
  });

  it('should be able to make onBlur action', () => {
    component.onBlur();
    expect(projectService.updateIssue).toHaveBeenCalled();
  });
  it('should be able to change title', () => {
    component.issue = {
      id: '',
      title: 'New title',
      type: IssueType.BUG,
      status: IssueStatus.BACKLOG,
      priority: IssuePriority.HIGH,
      listPosition: 0,
      description: '',
      estimate: 0,
      timeSpent: 0,
      timeRemaining: 0,
      createdAt: '',
      updatedAt: '',
      reporterId: '',
      userIds: [],
      comments: [],
      projectId: ''
    };
    component.ngOnChanges({
      issue: new SimpleChange(null, {title: 'New title'}, null)
    });
    expect(component.titleControl.value).toEqual('New title');
  });
  it('should not be able to change title', () => {
    component.issue = {
      id: '',
      title: 'New title 2',
      type: IssueType.BUG,
      status: IssueStatus.BACKLOG,
      priority: IssuePriority.HIGH,
      listPosition: 0,
      description: '',
      estimate: 0,
      timeSpent: 0,
      timeRemaining: 0,
      createdAt: '',
      updatedAt: '',
      reporterId: '',
      userIds: [],
      comments: [],
      projectId: ''
    };

    const expected = {title: 'New title'};

    component.ngOnChanges({
      issue: new SimpleChange(expected, expected, null)
    });
    expect(component.titleControl.value).toEqual('test');
  });
});
Example #8
Source File: vg-scrub-bar-cue-points.ts    From ngx-videogular with MIT License 5 votes vote down vote up
ngOnChanges(changes: { [propName: string]: SimpleChange }) {
    if (changes['vgCuePoints'].currentValue) {
      this.updateCuePoints();
    }
  }
Example #9
Source File: load-component.service.ts    From sba-angular with MIT License 5 votes vote down vote up
private _bindComponent(options: LoadComponentOptions, loadedComponent: LoadedComponent, initialLoad: boolean) {
        if (!initialLoad) {
            this.unbindComponent(loadedComponent);
        }
        const ngOnChanges: (changes: SimpleChanges) => void = loadedComponent.componentRef.instance.ngOnChanges;
        let simpleChanges: SimpleChanges | undefined;
        const makeSimpleChanges = Utils.isFunction(ngOnChanges) && !!options.inputs;
        if (!!options.inputs) {
            // Assign inputs and generate SimpleChanges if required
            Object.keys(options.inputs).forEach(name => {
                if (makeSimpleChanges) {
                    const previousValue = initialLoad ? undefined : loadedComponent.componentRef.instance[name];
                    const currentValue = options.inputs![name];
                    if (initialLoad || currentValue !== previousValue) {
                        if (!simpleChanges) {
                            simpleChanges = {};
                        }
                        simpleChanges[name] = new SimpleChange(previousValue, currentValue, initialLoad);
                    }
                }
                loadedComponent.componentRef.instance[name] = options.inputs![name];
            });
        }
        if (!!options.outputs) {
            Object.keys(options.outputs).forEach(name => {
                const eventEmitter: EventEmitter<any> = loadedComponent.componentRef.instance[name];
                if (eventEmitter) {
                    const subscription = eventEmitter.subscribe(options.outputs![name]);
                    if (!loadedComponent.subscriptions) {
                        loadedComponent.subscriptions = subscription;
                    }
                    else {
                        loadedComponent.subscriptions.add(subscription);
                    }
                }
            });
        }
        if (simpleChanges) {
            ngOnChanges.call(loadedComponent.componentRef.instance, simpleChanges);
        }
    }
Example #10
Source File: timeline.component.ts    From sba-angular with MIT License 5 votes vote down vote up
/**
     * Return true if there are actual changes in the data
     * (in particular will ignore data refresh which change nothing)
     * @param change
     */
    protected checkDataChanges(change: SimpleChange): boolean {
        const previousValue = change.previousValue as TimelineSeries[] | undefined;
        const currentValue = change.currentValue as TimelineSeries[] | undefined;

        // Ignore null/undefined difference cause by | async
        // See: https://github.com/angular/angular/issues/16982
        if(currentValue === null && previousValue === undefined || currentValue === undefined && previousValue === null)
            return false;

        // Else, if one of them is null/undefined (or difference in length), there's clearly a change
        if(!previousValue || !currentValue || previousValue.length !== currentValue.length)
            return true;

        // If both defined and same size, we need to compare the data piece by piece
        for(let i=0; i<currentValue.length; i++) {

            const previousSeries = previousValue[i];
            const currentSeries = currentValue[i];
            if(previousSeries.name !== currentSeries.name
                || previousSeries.primary !== currentSeries.primary
                || previousSeries.areaStyles !== currentSeries.areaStyles
                || previousSeries.lineStyles !== currentSeries.lineStyles
                || previousSeries.dates.length !== currentSeries.dates.length) {
                return true;
            }
            for(let j=0; j<previousSeries.dates.length; j++) {
                if(previousSeries.dates[j].value !== currentSeries.dates[j].value
                    || previousSeries.dates[j].date.getTime() !== currentSeries.dates[j].date.getTime()){
                    return true;
                }
            }
        }

        return false;
    }
Example #11
Source File: monaco-editor-base.component.ts    From ng-util with MIT License 5 votes vote down vote up
ngOnChanges(changes: { [P in keyof this]?: SimpleChange } & SimpleChanges): void {
    const allKeys = Object.keys(changes);
    if (allKeys.length === 1 && allKeys[0] === 'disabled') return;
    this.updateOptions();
  }
Example #12
Source File: ngx-tippy.directive.ts    From ngx-tippy-wrapper with MIT License 5 votes vote down vote up
private handleClassChanges({ previousValue, currentValue }: SimpleChange) {
    this.removeClassName(this.tippyInstance, previousValue);
    this.setClassName(this.tippyInstance, currentValue);
  }
Example #13
Source File: ngx-tippy.directive.ts    From ngx-tippy-wrapper with MIT License 5 votes vote down vote up
private handlePropsChanges({ currentValue }: SimpleChange) {
    this.tippyName && this.ngxTippyService.setProps(this.tippyName, currentValue);
  }
Example #14
Source File: ngx-tippy.directive.ts    From ngx-tippy-wrapper with MIT License 5 votes vote down vote up
private handleNameChanges({ previousValue, currentValue }: SimpleChange) {
    const tippyInstances = this.cachedTippyInstances();
    if (!tippyInstances || !this.tippyInstance) return;

    this.deleteEntryInStorage(tippyInstances, previousValue);
    this.tippyInstance = { ...this.tippyInstance, tippyName: currentValue };
    tippyInstances.set(currentValue, this.tippyInstance);
  }
Example #15
Source File: ngx-annotate-text.component.spec.ts    From ngx-annotate-text with MIT License 4 votes vote down vote up
describe('NgxAnnotateTextComponent', () => {
  let component: NgxAnnotateTextComponent;
  let fixture: ComponentFixture<NgxAnnotateTextComponent>;

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

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

  });

  it('should display the whole text when there are no initial annotations', () => {
    const text = 'On August 1, we went on vacation to Barcelona, Spain. Our flight took off at 11:00 am.';

    component.text = text;
    fixture.detectChanges();

    const textSpanElement = fixture.debugElement.nativeElement.querySelector('span:first-of-type');
    expect(textSpanElement.textContent).toBe(text);
  });

  it('should display the whole given text as a single annotated token', () => {
    const annotations = [
      new Annotation(0, 86, 'Annotation', 'red'),
    ];
    const text = 'On August 1, we went on vacation to Barcelona, Spain. Our flight took off at 11:00 am.';

    component.annotations = annotations;
    component.text = text;
    fixture.detectChanges();

    expect(component.tokens.length).toBe(annotations.length);
    expect(component.tokens[0] instanceof Annotation).toBeTrue();
    expect((component.tokens[0] as Annotation).text).toBe(text);
  });

  // it('should correctly determine the type of a token', () => {
  //   const annotation: Annotation = new Annotation(0, 5, 'Token', 'black');
  //   annotation.text = 'Hello';

  //   expect(component.isAnnotation(annotation)).toBeTrue();
  //   expect(component.isAnnotation('Hello')).toBeFalse();
  // });

  it('should emit an empty list of annotations if the only annotation has been removed', () => {
    spyOn(component.annotationsChange, 'emit');
    const annotations = [
      new Annotation(36, 45, 'City', 'red'),
    ];
    const text = 'On August 1, we went on vacation to Barcelona, Spain. Our flight took off at 11:00 am.';

    component.annotations = annotations;
    component.text = text;
    component.onRemoveAnnotation(annotations[0]);
    fixture.detectChanges();

    expect(component.annotationsChange.emit).toHaveBeenCalledWith([]);
    expect(component.annotations.length).toBe(0);
  });

  it('should emit the list of remaining annotations if an annotation has been removed', () => {
    spyOn(component.annotationsChange, 'emit');
    const annotations = [
      new Annotation(36, 45, 'City', 'red'),
      new Annotation(47, 52, 'Country', 'red'),
    ];
    const text = 'On August 1, we went on vacation to Barcelona, Spain. Our flight took off at 11:00 am.';

    component.annotations = annotations;
    component.text = text;
    component.onRemoveAnnotation(annotations[0]);
    fixture.detectChanges();

    expect(component.annotationsChange.emit).toHaveBeenCalledWith([annotations[1]]);
    expect(component.annotations.length).toBe(1);
  });

  it('should recompute the list of tokens if the text input has changed', () => {
    component.annotations = [
      new Annotation(0, 5, 'Token', 'red'),
    ];
    component.text = 'Hello, world';
    fixture.detectChanges();

    expect(component.tokens.length).toBe(2);
    expect((component.tokens[0] as Annotation).text).toBe('Hello');

    component.text = 'Now, with an updated message.';
    component.ngOnChanges({
      text: new SimpleChange('Hello, world', 'Now, with an updated message.', false),
    });
    fixture.detectChanges();

    expect(component.tokens.length).toBe(2);
    expect((component.tokens[0] as Annotation).text).toBe('Now, ');
  });

  it('should recompute the list of tokens if the annotations input has changed', () => {
    component.annotations = [
      new Annotation(0, 5, 'Token1', 'red'),
    ];
    component.text = 'Hello, world';
    fixture.detectChanges();

    expect(component.tokens.length).toBe(2);
    expect((component.tokens[0] as Annotation).text).toBe('Hello');

    component.annotations = [
      new Annotation(0, 5, 'Token1', 'red'),
      new Annotation(7, 12, 'Token2', 'red'),
    ];
    component.ngOnChanges({
      annotations: new SimpleChange([], [], false),
    });
    fixture.detectChanges();

    expect(component.tokens.length).toBe(3);
    expect((component.tokens[0] as Annotation).text).toBe('Hello');
    expect(component.tokens[1]).toBe(', ');
    expect((component.tokens[2] as Annotation).text).toBe('world');
  });

  describe('getCurrentTextSelection()', () => {

    it('should return `undefined` if no text is selected', () => {
      const text = 'On August 1, we went on vacation to Barcelona, Spain. Our flight took off at 11:00 am.';

      component.text = text;
      const selection = window.getSelection();
      selection!.removeAllRanges();
      fixture.detectChanges();

      expect(component.getCurrentTextSelection()).toBeUndefined();
    });

    it('should return the correct boundaries if the whole text is selected', () => {
      const text = 'On August 1, we went on vacation to Barcelona, Spain. Our flight took off at 11:00 am.';

      component.text = text;
      fixture.detectChanges();

      const node = fixture.debugElement.nativeElement.querySelector('span:first-of-type');
      const selection = window.getSelection();
      const range = document.createRange();
      range.selectNodeContents(node);
      selection!.removeAllRanges();
      selection!.addRange(range);
      fixture.detectChanges();

      expect(component.getCurrentTextSelection()!.startIndex).toBe(0);
      expect(component.getCurrentTextSelection()!.endIndex).toBe(text.length);
    });

    it('should return the correct boundaries if the beginning of the text is selected', () => {
      const text = 'On August 1, we went on vacation to Barcelona, Spain. Our flight took off at 11:00 am.';

      component.text = text;
      fixture.detectChanges();

      selectTextRangeInDocument(0, 2);
      fixture.detectChanges();

      expect(component.getCurrentTextSelection()!.startIndex).toBe(0);
      expect(component.getCurrentTextSelection()!.endIndex).toBe(2);
    });

    it('should return the correct boundaries if the middle of the text is selected', () => {
      const text = 'On August 1, we went on vacation to Barcelona, Spain. Our flight took off at 11:00 am.';

      component.text = text;
      fixture.detectChanges();

      selectTextRangeInDocument(3, 11);
      fixture.detectChanges();

      expect(component.getCurrentTextSelection()!.startIndex).toBe(3);
      expect(component.getCurrentTextSelection()!.endIndex).toBe(11);
    });

    it('should return the correct boundaries if the end of the text is selected', () => {
      const text = 'On August 1, we went on vacation to Barcelona, Spain. Our flight took off at 11:00 am.';

      component.text = text;
      fixture.detectChanges();

      selectTextRangeInDocument(76, 86);
      fixture.detectChanges();

      expect(component.getCurrentTextSelection()!.startIndex).toBe(76);
      expect(component.getCurrentTextSelection()!.endIndex).toBe(86);
    });

  });

  describe('isOverlappingWithExistingAnnotations()', () => {

    it('should return false if there is no annotation that overlaps with the selection', () => {
      const selection: ISelection = {
        startIndex: 5,
        endIndex: 9,
      };

      component.annotations = [
        new Annotation(0, 5, 'Article', 'yellow'),
        new Annotation(9, 11, 'Article', 'yellow'),
        new Annotation(16, 22, 'Article', 'yellow'),
      ];

      expect(component.isOverlappingWithExistingAnnotations(selection)).toBeFalse();
    });

    /**
     * Annotation:  ####
     * Selection:   ####
     */
    it('should return true if there exists an annotation with identical start and end index', () => {
      const selection: ISelection = {
        startIndex: 5,
        endIndex: 12,
      };

      component.annotations = [
        new Annotation(5, 12, 'Noun', 'blue'),
      ];

      expect(component.isOverlappingWithExistingAnnotations(selection)).toBeTrue();
    });

    /**
     * Annotation:    ####
     * Selection:   ####
     */
    it('should return true if the selection partially overlaps with an existing annotation', () => {
      const selection: ISelection = {
        startIndex: 0,
        endIndex: 6,
      };

      component.annotations = [
        new Annotation(4, 8, 'Verb', 'red'),
      ];

      expect(component.isOverlappingWithExistingAnnotations(selection)).toBeTrue();
    });

    /**
     * Annotation:  ####
     * Selection:     ####
     */
    it('should return true if the selection partially overlaps with an existing annotation', () => {
      const selection: ISelection = {
        startIndex: 6,
        endIndex: 12,
      };

      component.annotations = [
        new Annotation(4, 8, 'Adjective', 'orange'),
      ];

      expect(component.isOverlappingWithExistingAnnotations(selection)).toBeTrue();
    });

    /**
     * Annotation:  ####
     * Selection:    ##
     */
    it('should return true if the selection is part of an existing annotation', () => {
      const selection: ISelection = {
        startIndex: 6,
        endIndex: 8,
      };

      component.annotations = [
        new Annotation(4, 10, 'Adjective', 'orange'),
      ];

      expect(component.isOverlappingWithExistingAnnotations(selection)).toBeTrue();
    });

    /**
     * Annotation:   ##
     * Selection:   ####
     */
    it('should return true if the selection is part of an existing annotation', () => {
      const selection: ISelection = {
        startIndex: 4,
        endIndex: 10,
      };

      component.annotations = [
        new Annotation(6, 8, 'Adjective', 'orange'),
      ];

      expect(component.isOverlappingWithExistingAnnotations(selection)).toBeTrue();
    });

  });

  function selectTextRangeInDocument(start: number, end: number): void {
    const node = fixture.debugElement.nativeElement.querySelector('span.unlabeled');
    const selection = window.getSelection();
    const range = document.createRange();
    range.setStart(node.childNodes[0], start);
    range.setEnd(node.childNodes[0], end);
    selection!.removeAllRanges();
    selection!.addRange(range);
  }
});
Example #16
Source File: facet-list.spec.ts    From sba-angular with MIT License 4 votes vote down vote up
describe('BsFacetList', () => {
    let context: BsFacetList;
    let fixture: ComponentFixture<BsFacetList>;

    beforeEach(waitForAsync(() => {
        TestBed.configureTestingModule({
            declarations: [BsFacetList, ValuePipe, NumberPipe],
            imports: [
                CommonModule,
                IntlModule.forRoot(AppLocalesConfig),
                BsFacetModule.forRoot()
            ],
            providers: [
                HttpHandler,
                FacetService,
                SearchService,
                LoginService,
                AuthenticationService,
                Overlay,
                ValuePipe,
                NumberPipe,
                {provide: Router, useClass: RouterStub},
                {provide: AuthService, useValue: {}},
                {provide: START_CONFIG, useValue: startConfig},
                {provide: MODAL_LOGIN, useValue: {}},
                {provide: MODAL_CONFIRM, useValue: {}},
                {provide: MODAL_PROMPT, useValue: {}},
            ]
        }).compileComponents();
    }));

    beforeEach(() => {
        fixture = TestBed.createComponent(BsFacetList);
        context = fixture.debugElement.componentInstance;
    });

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

    it('should display data', () => {
        // stub FacetService to returns mocked data
        const service = TestBed.inject(FacetService);
        spyOn(service, 'getAggregation').and.returnValue(AGGREGATION_GEO);
        spyOn(context, 'refreshFiltered').and.callThrough();

        // @Input()
        context.name = "Geo";
        context.results = RESULTS as any;
        context.searchItems.selected = true;

        expect(context.data()).toBeUndefined();
        expect(context.resultsLength).toEqual(0);
        expect(context.isHidden()).toBeTrue();

        context.ngOnChanges({results: {} as SimpleChange});
        fixture.detectChanges();

        // DOM expectations
        // - 11 rows
        // - no selected rows
        const DOM = fixture.nativeElement;
        expect(DOM.querySelectorAll(".facet-row").length).toEqual(11);
        expect(DOM.querySelectorAll(".list-group-item-primary").length).toEqual(0);

        // Components expectations
        expect(context.getName()).toEqual("Geo");
        expect(context.data()?.name).toEqual("Geo");
        expect(context.resultsLength).toEqual(11);
        expect(context.isHidden()).toBeFalse();

        expect(context.actions.length).toBeGreaterThan(0);
        expect(context.searchItems.selected).toBeFalse();
        expect(context.filtered.length).toEqual(0);
        expect(context.searchQuery.value).toEqual("");
        expect(context.noResults).toBeFalse();
        expect(context.suggestions$.getValue().length).toEqual(0);

        expect(context.refreshFiltered).toHaveBeenCalledTimes(1);
    });

    it("should mark an item selected on user's click", () => {
        // stub FacetService to returns mocked data
        const service = TestBed.inject(FacetService);
        spyOn(service, 'getAggregation').and.returnValue(AGGREGATION_CONCEPTS);
        spyOn(context, 'refreshFiltered').and.callThrough();
        spyOn(context, 'ngOnChanges').and.callThrough();
        spyOn(context, 'selectItem').and.callThrough();

        // @Input()
        context.name = 'Geo';
        context.results = RESULTS as any;
        context.searchItems.selected = true;

        // trigger manually an ngOnChanges's event
        context.ngOnChanges({results: {} as SimpleChange});
        fixture.detectChanges();

        // user's click on 4th row
        const el: HTMLElement | null = fixture.nativeElement.querySelectorAll("div.facet-row")[4];
        el?.click();

        fixture.detectChanges();

        // DOM expectations
        // - 4th row is selected
        // - only 1 row selected
        // - selected row's title has changed from "select" to "unselect"
        const selectedElements = fixture.nativeElement.querySelectorAll(".list-group-item-primary");

        expect(selectedElements.length).toEqual(1);
        expect(el?.classList).toContain("list-group-item-primary");
        expect(el?.title).toEqual("msg#facet.itemUnselect");

        // Component expectations
        expect(context.isSelected(context.items$.getValue()[4])).toBeTrue();
        expect(context.selected.length).toEqual(1);

        expect(context.selectItem).toHaveBeenCalledTimes(1);
        expect(context.ngOnChanges).toHaveBeenCalledTimes(1);
    })
});
Example #17
Source File: vg-scrub-bar-cue-points.spec.ts    From ngx-videogular with MIT License 4 votes vote down vote up
// tslint:disable:ban-types
describe('Scrub bar current time', () => {
  let scrubBarCuePoints: VgScrubBarCuePoints;
  let ref: ElementRef;
  let api: VgAPI;

  beforeEach(() => {
    ref = {
      nativeElement: {
        getAttribute: (name) => {
          return name;
        },
        subscriptions: {
          loadedMetadata: {
            subscribe: () => {
            }
          }
        }
      }
    };

    api = new VgAPI();

    scrubBarCuePoints = new VgScrubBarCuePoints(ref, api);
  });

  it('Should create cue points when metadata is loaded', () => {
    const cps: Object = {
      length: 3
    };
  
    const cp1: TextTrackCue = ({ startTime: 1 } as any);
    const cp2: TextTrackCue = ({ startTime: 5, endTime: 10 } as any);
    const cp3: TextTrackCue = ({ startTime: 15, endTime: 20, text: '{value: \'custom params\'}' } as any);

    cps[0] = cp1;
    cps[1] = cp2;
    cps[2] = cp3;

    scrubBarCuePoints.vgCuePoints = (cps as TextTrackCueList);

    scrubBarCuePoints.target = {
      time: {
        total: 100000
      }
    };

    scrubBarCuePoints.ngOnChanges({ vgCuePoints: ({ currentValue: cps } as SimpleChange) });

    expect((scrubBarCuePoints.vgCuePoints[0] as any).$$style).toEqual({ width: '1%', left: '1%' });
    expect((scrubBarCuePoints.vgCuePoints[1] as any).$$style).toEqual({ width: '5%', left: '5%' });
    expect((scrubBarCuePoints.vgCuePoints[2] as any).$$style).toEqual({ width: '5%', left: '15%' });
  });

  it('Should not calculate style position if there is not duration on media', () => {
    const cps: Object = {
      length: 3
    };
    const cp1: TextTrackCue = ({ startTime: 1 } as TextTrackCue);
    const cp2: TextTrackCue = ({ startTime: 5, endTime: 10 } as TextTrackCue);
    const cp3: TextTrackCue = ({ startTime: 15, endTime: 20, text: '{value: \'custom params\'}' } as any);

    cps[0] = cp1;
    cps[1] = cp2;
    cps[2] = cp3;

    scrubBarCuePoints.vgCuePoints = (cps as TextTrackCueList);

    scrubBarCuePoints.target = {
      time: {
        total: 0
      }
    };

    scrubBarCuePoints.ngOnChanges({ vgCuePoints: ({ currentValue: cps } as SimpleChange) });

    expect((scrubBarCuePoints.vgCuePoints[0] as any).$$style).toEqual({ width: '0', left: '0' });
    expect((scrubBarCuePoints.vgCuePoints[1] as any).$$style).toEqual({ width: '0', left: '0' });
    expect((scrubBarCuePoints.vgCuePoints[2] as any).$$style).toEqual({ width: '0', left: '0' });
  });

  it('Should do nothing if there are no cue points', () => {

    const ucspy = spyOn(scrubBarCuePoints, 'updateCuePoints');
    scrubBarCuePoints.vgCuePoints = null;
    scrubBarCuePoints.onLoadedMetadata();
    scrubBarCuePoints.ngOnChanges({ vgCuePoints: ({ currentValue: null } as SimpleChange) });

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

  it('Should handle after view init event', () => {
    spyOn(scrubBarCuePoints.API, 'getMediaById').and.callFake(
      () => {
        return ref.nativeElement;
      }
    );

    spyOn(ref.nativeElement.subscriptions.loadedMetadata, 'subscribe').and.callThrough();

    scrubBarCuePoints.onPlayerReady();

    expect(ref.nativeElement.subscriptions.loadedMetadata.subscribe).toHaveBeenCalled();
  });
});