Angular Jest 测试绑定window:scroll的@HostListener指令事件触发方法
Angular滚动自定义指令的Jest测试实现方案
核心问题的解决逻辑
- 绑定在
window:scroll上的@HostListener回调,不需要硬编码直接调用,手动向window派发原生scroll事件即可触发,和真实运行的逻辑完全一致 - 指令实例不需要额外在测试组件中暴露引用,通过Angular的
DebugElement查询能力,直接从渲染树中拿到挂载的指令对象 - 测试前必须手动触发Angular的视图生命周期,否则
ngAfterViewInit不会执行,breakpointOffset会保持undefined,所有判断逻辑都会失效
可直接复用的测试代码实现
// 依赖导入 import { Component, ViewChild, ElementRef, Directive, HostListener } from '@angular/core'; import { TestBed, ComponentFixture } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; // 待测试的目标指令(修正了原代码中setAttribute的语法错误) @Directive({ selector: '[directiveSelector]', }) export class Directive { private breakpointOffset: number; private fixed = false; constructor(private readonly elementRef: ElementRef) {} ngAfterViewInit() { this.breakpointOffset = this.elementRef.nativeElement.offsetTop; } @HostListener('window:scroll') addScrollTrigger() { if (!this.fixed && window.pageYOffset > this.breakpointOffset) { this.elementRef.nativeElement.setAttribute( 'style', 'position: fixed' ); this.fixed = true; } if (this.fixed && window.pageYOffset <= this.breakpointOffset) { this.elementRef.nativeElement.setAttribute('style', ''); this.fixed = false; } } } // 承载指令的测试组件 @Component({ template: ` <div #container directiveSelector></div> `, }) class TestComponent { @ViewChild('container') container: ElementRef; } describe('Directive', () => { let fixture: ComponentFixture<TestComponent>; let component: TestComponent; let directiveInstance: Directive; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [TestComponent, Directive], }).compileComponents(); fixture = TestBed.createComponent(TestComponent); component = fixture.componentInstance; // 触发首次变更检测,完成视图初始化,执行ngAfterViewInit钩子 fixture.detectChanges(); // 从渲染树中查询被指令挂载的节点,获取指令实例 directiveInstance = fixture.debugElement .query(By.directive(Directive)) .injector.get(Directive); })); it('滚动位置超过元素偏移值时,为元素添加fixed定位样式', () => { // mock元素的offsetTop值,避免jsdom默认返回0导致的边界判断偏差 const mockOffsetTop = 100; jest.spyOn(component.container.nativeElement, 'offsetTop', 'get').mockReturnValue(mockOffsetTop); // 再次触发变更检测,让ngAfterViewInit读取到mock后的正确偏移值 fixture.detectChanges(); // 模拟滚动位置超过预设偏移值 Object.defineProperty(window, 'pageYOffset', { value: 150, writable: true, }); // 手动向window派发原生scroll事件,触发HostListener绑定的回调 window.dispatchEvent(new Event('scroll')); // 断言样式生效 expect(component.container.nativeElement.getAttribute('style')).toContain('position: fixed'); }); it('滚动位置回到元素偏移值以下时,清除元素的fixed定位样式', () => { // 先复现fixed激活状态 const mockOffsetTop = 100; jest.spyOn(component.container.nativeElement, 'offsetTop', 'get').mockReturnValue(mockOffsetTop); fixture.detectChanges(); Object.defineProperty(window, 'pageYOffset', { value: 150 }); window.dispatchEvent(new Event('scroll')); // 模拟滚动回到偏移值以下 Object.defineProperty(window, 'pageYOffset', { value: 50 }); window.dispatchEvent(new Event('scroll')); // 断言样式被清除 expect(component.container.nativeElement.getAttribute('style')).not.toContain('position: fixed'); }); });
常见踩坑注意事项
- jsdom测试环境中元素的
offsetTop默认返回0,不做mock的话,只要滚动值大于0就会触发fixed逻辑,完全失去边界判断的测试意义 - 不建议直接调用指令内部的私有
addScrollTrigger方法,手动派发事件的测试链路和用户真实滚动的行为完全一致,能避免测试假通过的问题 - 如果遇到事件派发后回调不执行的情况,可在事件派发后补充一次
fixture.detectChanges(),等待Angular完成变更检测周期
内容的提问来源于stack exchange,提问作者headofhappiness
相关产品推荐
相关产品推荐

