【发布时间】:2021-08-04 06:57:35
【问题描述】:
我有一个指令可以记住某些 div 的滚动位置。
指令
constructor(
private elementRef: ElementRef,
private restoreValueService: KeyValueMapService
) {}
ngOnInit(): void {
const debounceTimeValue = 200;
console.log(this.elementRef.nativeElement);
fromEvent(this.elementRef.nativeElement, 'scroll').pipe(
takeUntil(this.destroyed$),
debounceTime(debounceTimeValue)
).subscribe((event: Event) => this.onScroll());
}
ngOnDestroy(): void {
this.destroyed$.next(true);
this.destroyed$.complete();
}
onScroll(): void {
console.log('on Scroll');
this.scrollValue = this.elementRef.nativeElement.scrollTop;
this.restoreValueService.values.set('scroll', this.scrollValue);
}
我也有 Map 的小服务,应该接收滚动值:
export class KeyValueMapService {
values: Map<string, any> = new Map();
}
我正在尝试使用fakeAsync() 和tick() 对其进行测试,但是当我运行此测试时,期望在回调方法onScroll() 之前运行并且测试失败,因为地图还没有滚动值。
规格
fdescribe('RestoreScrollDirective', () => {
let fixture: ComponentFixture<TestComponent>;
let component: TestComponent;
let debugElement: DebugElement;
let innerDiv: DebugElement;
let keyValueService: KeyValueMapService;
beforeEach(() => {
keyValueService = new KeyValueMapService();
TestBed.configureTestingModule({
declarations: [ TestComponent, RestoreScrollDirective ],
providers: [ {provide: KeyValueMapService, useValue: keyValueService}]
}).compileComponents();
fixture = TestBed.createComponent(TestComponent);
component = fixture.componentInstance;
debugElement = fixture.debugElement;
innerDiv = debugElement.query(By.css('.outer-div'));
});
it('Should save in service its last scroll position', fakeAsync(() => {
fixture.detectChanges();
// I scroll div element which holds directive
const scrollPosition = 250;
const element = innerDiv.nativeElement as HTMLDivElement;
element.scrollTo(0, scrollPosition);
fixture.detectChanges();
// I simulate time passage needed to my callback run, due to the debounce time
tick(201);
fixture.detectChanges();
console.log('Exceptations begin'); // this logs earlier than 'on Scroll'
const map = keyValueService.values;
expect(map.has('scroll')).toBe(true);
expect(map.get('scroll')).toBe(scrollPosition);
}));
});
任何人都可以向我解释为什么我的期望在onScroll() 方法之前执行? 'Exceptionations begin' 的记录早于 on Scroll,即使我使用的 tick 的值高于去抖动时间。
【问题讨论】:
标签: angular unit-testing testing rxjs