How to write test cases for Subscriber and timeout inside ngOnit method?

后端 未结 1 1568
长情又很酷
长情又很酷 2021-01-26 01:35

I have a class in angular8 application with following ngOnit method

  ngOnInit(): void {
    this.setCustomizedValues();
    this.sub = PubSub.subscribe(\'highlig         


        
相关标签:
1条回答
  • 2021-01-26 02:06

    Since you're messing with the DOM, ngOnInit can be too early for that. The DOM has not yet been painted. Try moving the logic to ngAfterViewInit

    ngAfterViewInit() {
        this.sub = PubSub.subscribe('highlightEntity', (subId, entityIdentifier: string) => {
          document.querySelector(entityIdentifier).classList.add('highlight');
    
          setTimeout(() => {
            document.querySelector(entityIdentifier).classList.remove('highlight');
          }, 2000);
        });
    }
    

    And to test the setTimeout, you can use fakeAsync and tick.

    import { fakeAsync, tick } from '@angular/core/testing';
    ...
    it('should initialize with minimum input', fakeAsync(() => {
          // Triggers ngOnInit
          fixture.detectChanges();
          // do your assertions for ngAfterViewInit
          // make 2s pass in a fake way
          tick(2000);
          // do your assertions for the setTimeout callback
          expect(fixture.componentInstance.customized).toEqual({});
        }));
    
    0 讨论(0)
提交回复
热议问题