【发布时间】: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 typescript jestjs