【问题标题】:timeout function inside directive not called指令内的超时函数未调用
【发布时间】:2021-12-08 01:52:07
【问题描述】:

我想测试一个简单的 AutoScrollDirective。

@Directive({
  selector: '[appAutoScroll]',
})
export class AutoScrollDirective implements AfterViewInit {
  constructor(private element: ElementRef<HTMLElement>) {}

  @Input()
  delay = 100;

  ngAfterViewInit(): void {
    setTimeout(
      () => this.element.nativeElement.scrollIntoView({ behavior: 'smooth', block: 'start', inline: 'nearest' }),
      this.delay
    );
  }
}

如您所见,它包含一个 setTimeout。我认为这可以用 fakeAsync 来处理。

@Component({
  template: `<div appAutoScroll></div>`,
})
class TestAutoScrollDirectiveComponent implements AfterViewInit {
  ngAfterViewInit(): void {}
}

describe('AutoScrollDirective', () => {
  let fixture: ComponentFixture<TestAutoScrollDirectiveComponent>;
  let component: TestAutoScrollDirectiveComponent;

  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [AutoScrollDirective, TestAutoScrollDirectiveComponent],
      imports: [BrowserDynamicTestingModule],
    });

    fixture = TestBed.createComponent(TestAutoScrollDirectiveComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should call scrollIntoView of the element', fakeAsync(() => {
    const scrollIntoViewMock = jest.fn();
    HTMLElement.prototype.scrollIntoView = scrollIntoViewMock;
    component.ngAfterViewInit();
    tick();
    expect(scrollIntoViewMock).toHaveBeenCalled();
  }));
});

但是,timeOut 中的函数永远不会被调用。经过一些调试,我发现它到达了 ngAfterViewInit 并调用了 setTimeout 但没有任何反应。

编辑:

我已经尝试了this post 的解决方案,但我同意它不是一个合适的解决方案。它现在可以工作,但我会保持打开状态,以便找到更好的。

【问题讨论】:

  • ngAfterViewInit 不是指令的生命周期钩子,它仅适用于组件
  • Angular documentation中所述

标签: angular typescript jestjs


【解决方案1】:

尝试使用:

tick(101);

而不是

 tick();

【讨论】:

  • 不,没有任何改变。仍然没有调用该函数。
  • 你能告诉我测试的结果是什么,它是否失败以及出现什么错误?
  • 预期来电 >= 1 接听电话 = 0
猜你喜欢
  • 2016-04-21
  • 2018-07-30
  • 2016-05-30
  • 1970-01-01
  • 1970-01-01
  • 2019-08-24
  • 2019-03-11
相关资源
最近更新 更多